<!doctype html>
<html
  lang="en"
  x-data="{ darkMode: JSON.parse(localStorage.getItem('darkMode') || 'false') }"
  x-bind:class="darkMode ? 'dark' : ''"
  x-init="$watch('darkMode', val => localStorage.setItem('darkMode', val))"
>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>MCP Gateway Admin</title>

    <!-- Security meta tags for static analysis tools (complement HTTP headers) -->
    <meta
      http-equiv="Content-Security-Policy"
      content="default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdnjs.cloudflare.com https://cdn.tailwindcss.com https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com; img-src 'self' data: https:; font-src 'self' data:; connect-src 'self' ws: wss: https:; frame-ancestors 'none';"
    />
    <meta http-equiv="X-Frame-Options" content="DENY" />
    <meta http-equiv="X-Content-Type-Options" content="nosniff" />
    <meta http-equiv="X-XSS-Protection" content="1; mode=block" />
    <meta http-equiv="X-Download-Options" content="noopen" />
    <meta
      http-equiv="Referrer-Policy"
      content="strict-origin-when-cross-origin"
    />
    <!-- Favicon -->
    <link
      rel="icon"
      type="image/png"
      sizes="32x32"
      href="{{ root_path }}/static/favicon.ico"
    />
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
      tailwind.config = {
        darkMode: "class",
      };
    </script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.18/codemirror.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.18/mode/javascript/javascript.min.js"></script>
    <script
      src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"
      defer
    ></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="{{ root_path }}/static/admin.js"></script>
    <link
      href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.18/codemirror.min.css"
      rel="stylesheet"
    />
    <link
      href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.18/theme/monokai.min.css"
      rel="stylesheet"
    />
    <link href="{{ root_path }}/static/admin.css" rel="stylesheet" />
    <style>
      /* HTMX indicator visibility for bulk import only */
      #bulk-import-indicator {
        display: none;
      }
      .htmx-request #bulk-import-indicator {
        display: flex !important;
      }
    </style>
  </head>

  <body class="bg-gray-100 dark:bg-gray-900">
    <div class="w-full max-w-screen-2xl mx-auto px-4 py-8">
      <header class="mb-8">
        <h1 class="text-3xl font-bold text-gray-800 dark:text-gray-200">
          MCP Context Forge - Gateway Administration
        </h1>

        <p class="text-gray-600 dark:text-gray-400">
          Manage tools, resources, prompts, servers, and federated gateways
          (remote MCP servers)
          <span class="mx-2 text-gray-400">|</span>
          <a
            href="https://ibm.github.io/mcp-context-forge/"
            target="_blank"
            class="text-indigo-600 dark:text-indigo-500 hover:underline"
          >
            Docs</a
          >
          <span class="mx-2 text-gray-400">|</span>
          <a
            href="https://github.com/IBM/mcp-context-forge"
            target="_blank"
            class="text-indigo-600 dark:text-indigo-500 hover:underline"
            >⭐ Star mcp-context-forge on GitHub</a
          >
        </p>
      </header>

      <!-- Tabs -->
      <div class="mb-8">
        <div class="border-b border-gray-200">
          <nav class="-mb-px flex space-x-8">
            <a
              href="#catalog"
              id="tab-catalog"
              data-testid="servers-tab"
              class="tab-link border-indigo-500 text-indigo-600 dark:text-indigo-500 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"
            >
              Virtual Servers Catalog
            </a>
            <a
              href="#tools"
              id="tab-tools"
              data-testid="tools-tab"
              class="tab-link border-transparent text-gray-500 dark:text-gray-300 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"
            >
              Global Tools
            </a>
            <a
              href="#resources"
              id="tab-resources"
              class="tab-link border-transparent text-gray-500 dark:text-gray-300 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"
            >
              Global Resources
            </a>
            <a
              href="#prompts"
              id="tab-prompts"
              class="tab-link border-transparent text-gray-500 dark:text-gray-300 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"
            >
              Global Prompts
            </a>
            <a
              href="#gateways"
              id="tab-gateways"
              data-testid="gateways-tab"
              class="tab-link border-transparent text-gray-500 dark:text-gray-300 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"
            >
              Gateways/MCP Servers
            </a>
            {% if a2a_enabled %}
            <a
              href="#a2a-agents"
              id="tab-a2a-agents"
              data-testid="a2a-agents-tab"
              class="tab-link border-transparent text-gray-500 dark:text-gray-300 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"
            >
              A2A Agents
            </a>
            {% endif %}
            <a
              href="#roots"
              id="tab-roots"
              class="tab-link border-transparent text-gray-500 dark:text-gray-300 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"
            >
              Roots
            </a>
            <a
              href="#metrics"
              id="tab-metrics"
              class="tab-link border-transparent text-gray-500 dark:text-gray-300 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"
            >
              Metrics
            </a>
            <a
              href="#logs"
              id="tab-logs"
              class="tab-link border-transparent text-gray-500 dark:text-gray-300 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"
            >
              Logs
            </a>
            <a
              href="#export-import"
              id="tab-export-import"
              class="tab-link border-transparent text-gray-500 dark:text-gray-300 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"
            >
              Export/Import
            </a>
            <!-- New Version tab (opens separate /version page) -->
            <a
              href="#version-info"
              id="tab-version-info"
              class="tab-link border-transparent text-gray-500 dark:text-gray-300 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"
            >
              Version and Environment Info
            </a>
            <button @click="darkMode = !darkMode" class="p-2">
              <span x-text="darkMode ? '☀️' : '🌙'"></span>
            </button>
          </nav>
        </div>
      </div>

      <!-- Logs Panel -->
      <div id="logs-panel" class="tab-panel hidden">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <div class="bg-white dark:bg-gray-800 shadow rounded-lg">
            <div class="px-4 py-5 sm:p-6">
              <h2
                class="text-lg font-medium text-gray-900 dark:text-white mb-4"
              >
                System Logs
              </h2>

              <!-- Log Filters -->
              <div class="mb-4 grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                  <label
                    class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >Level</label
                  >
                  <select
                    id="log-level-filter"
                    class="mt-1 block w-full border-gray-300 rounded-md shadow-sm dark:bg-gray-700 dark:border-gray-600"
                  >
                    <option value="">All Levels</option>
                    <option value="debug">Debug</option>
                    <option value="info">Info</option>
                    <option value="warning">Warning</option>
                    <option value="error">Error</option>
                    <option value="critical">Critical</option>
                  </select>
                </div>

                <div>
                  <label
                    class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >Entity Type</label
                  >
                  <select
                    id="log-entity-filter"
                    class="mt-1 block w-full border-gray-300 rounded-md shadow-sm dark:bg-gray-700 dark:border-gray-600"
                  >
                    <option value="">All Types</option>
                    <option value="tool">Tool</option>
                    <option value="resource">Resource</option>
                    <option value="server">Server</option>
                    <option value="gateway">Gateway</option>
                  </select>
                </div>

                <div>
                  <label
                    class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >Search</label
                  >
                  <input
                    type="text"
                    id="log-search"
                    placeholder="Search logs..."
                    class="mt-1 block w-full border-gray-300 rounded-md shadow-sm dark:bg-gray-700 dark:border-gray-600"
                  />
                </div>
              </div>

              <!-- Action Buttons -->
              <div class="mb-4 flex gap-2">
                <button
                  onclick="refreshLogs()"
                  class="px-3 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
                >
                  Refresh
                </button>
                <button
                  onclick="toggleLogStream()"
                  id="stream-toggle"
                  class="px-3 py-2 bg-green-600 text-white rounded hover:bg-green-700"
                >
                  Start Live Stream
                </button>
                <button
                  onclick="exportLogs('json')"
                  class="px-3 py-2 bg-gray-600 text-white rounded hover:bg-gray-700"
                >
                  Export JSON
                </button>
                <button
                  onclick="exportLogs('csv')"
                  class="px-3 py-2 bg-gray-600 text-white rounded hover:bg-gray-700"
                >
                  Export CSV
                </button>
                <button
                  onclick="showLogFiles()"
                  class="px-3 py-2 bg-purple-600 text-white rounded hover:bg-purple-700"
                >
                  Download Files
                </button>
              </div>

              <!-- Log Stats -->
              <div
                id="log-stats"
                class="mb-4 p-3 bg-gray-100 dark:bg-gray-700 rounded"
              >
                <span class="text-sm text-gray-600 dark:text-gray-300"
                  >Loading stats...</span
                >
              </div>

              <!-- Log Table -->
              <div class="overflow-x-auto">
                <table
                  class="min-w-full divide-y divide-gray-200 dark:divide-gray-700"
                >
                  <thead class="bg-gray-50 dark:bg-gray-700">
                    <tr>
                      <th
                        class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                      >
                        Time
                      </th>
                      <th
                        class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                      >
                        Level
                      </th>
                      <th
                        class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                      >
                        Entity
                      </th>
                      <th
                        class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                      >
                        Message
                      </th>
                    </tr>
                  </thead>
                  <tbody
                    id="logs-tbody"
                    class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700"
                  >
                    <!-- Logs will be inserted here -->
                  </tbody>
                </table>
              </div>

              <!-- Pagination -->
              <div class="mt-4 flex justify-between items-center">
                <div>
                  <span
                    id="log-count"
                    class="text-sm text-gray-600 dark:text-gray-300"
                    >0 logs</span
                  >
                </div>
                <div class="flex gap-2">
                  <button
                    onclick="previousLogPage()"
                    id="prev-page"
                    class="px-3 py-1 bg-gray-300 dark:bg-gray-600 rounded disabled:opacity-50"
                    disabled
                  >
                    Previous
                  </button>
                  <button
                    onclick="nextLogPage()"
                    id="next-page"
                    class="px-3 py-1 bg-gray-300 dark:bg-gray-600 rounded disabled:opacity-50"
                  >
                    Next
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Export/Import Panel -->
      <div id="export-import-panel" class="tab-panel hidden">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <div class="bg-white dark:bg-gray-800 shadow rounded-lg">
            <div class="px-4 py-5 sm:p-6">
              <h2
                class="text-lg font-medium text-gray-900 dark:text-white mb-6"
              >
                Configuration Export & Import
              </h2>

              <!-- Export Section -->
              <div class="mb-8">
                <h3
                  class="text-md font-medium text-gray-900 dark:text-white mb-4"
                >
                  📤 Export Configuration
                </h3>

                <!-- Export Options -->
                <div class="bg-gray-50 dark:bg-gray-700 p-4 rounded-lg mb-4">
                  <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
                      >
                        Entity Types
                      </label>
                      <div class="space-y-2">
                        <label class="flex items-center">
                          <input
                            type="checkbox"
                            id="export-tools"
                            checked
                            class="mr-2"
                          />
                          <span class="text-sm text-gray-600 dark:text-gray-300"
                            >Tools</span
                          >
                        </label>
                        <label class="flex items-center">
                          <input
                            type="checkbox"
                            id="export-gateways"
                            checked
                            class="mr-2"
                          />
                          <span class="text-sm text-gray-600 dark:text-gray-300"
                            >Gateways</span
                          >
                        </label>
                        <label class="flex items-center">
                          <input
                            type="checkbox"
                            id="export-servers"
                            checked
                            class="mr-2"
                          />
                          <span class="text-sm text-gray-600 dark:text-gray-300"
                            >Servers</span
                          >
                        </label>
                        <label class="flex items-center">
                          <input
                            type="checkbox"
                            id="export-prompts"
                            checked
                            class="mr-2"
                          />
                          <span class="text-sm text-gray-600 dark:text-gray-300"
                            >Prompts</span
                          >
                        </label>
                        <label class="flex items-center">
                          <input
                            type="checkbox"
                            id="export-resources"
                            checked
                            class="mr-2"
                          />
                          <span class="text-sm text-gray-600 dark:text-gray-300"
                            >Resources</span
                          >
                        </label>
                        <label class="flex items-center">
                          <input
                            type="checkbox"
                            id="export-roots"
                            checked
                            class="mr-2"
                          />
                          <span class="text-sm text-gray-600 dark:text-gray-300"
                            >Roots</span
                          >
                        </label>
                      </div>
                    </div>

                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
                      >
                        Filter Options
                      </label>
                      <div class="space-y-2">
                        <label class="flex items-center">
                          <input
                            type="checkbox"
                            id="export-include-inactive"
                            class="mr-2"
                          />
                          <span class="text-sm text-gray-600 dark:text-gray-300"
                            >Include Inactive</span
                          >
                        </label>
                        <label class="flex items-center">
                          <input
                            type="checkbox"
                            id="export-include-dependencies"
                            checked
                            class="mr-2"
                          />
                          <span class="text-sm text-gray-600 dark:text-gray-300"
                            >Include Dependencies</span
                          >
                        </label>
                      </div>

                      <div class="mt-3">
                        <label
                          class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                        >
                          Filter by Tags
                        </label>
                        <input
                          type="text"
                          id="export-tags"
                          placeholder="production,api,staging"
                          class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md text-sm bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                        />
                        <p
                          class="text-xs text-gray-500 dark:text-gray-400 mt-1"
                        >
                          Comma-separated tags
                        </p>
                      </div>
                    </div>

                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
                      >
                        Export Actions
                      </label>
                      <div class="space-y-2">
                        <button
                          id="export-all-btn"
                          class="w-full bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md text-sm font-medium"
                        >
                          📥 Export All Configuration
                        </button>
                        <button
                          id="export-selected-btn"
                          class="w-full bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-md text-sm font-medium"
                        >
                          📋 Export Selected Types
                        </button>
                      </div>

                      <div class="mt-4">
                        <div id="export-progress" class="hidden">
                          <div
                            class="text-sm text-gray-600 dark:text-gray-300 mb-1"
                          >
                            Exporting...
                          </div>
                          <div
                            class="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2"
                          >
                            <div
                              id="export-progress-bar"
                              class="bg-blue-600 h-2 rounded-full transition-all duration-300"
                              style="width: 0%"
                            ></div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- Import Section -->
              <div class="mb-8">
                <h3
                  class="text-md font-medium text-gray-900 dark:text-white mb-4"
                >
                  📥 Import Configuration
                </h3>

                <div class="bg-gray-50 dark:bg-gray-700 p-4 rounded-lg">
                  <!-- File Upload Area -->
                  <div class="mb-4">
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
                    >
                      Import File
                    </label>
                    <div
                      id="import-drop-zone"
                      class="border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg p-6 text-center hover:border-gray-400 dark:hover:border-gray-500 cursor-pointer"
                    >
                      <div class="space-y-2">
                        <svg
                          class="mx-auto h-12 w-12 text-gray-400"
                          stroke="currentColor"
                          fill="none"
                          viewBox="0 0 48 48"
                        >
                          <path
                            d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3-3m-3 3l3 3m-3-3V8"
                            stroke-width="2"
                            stroke-linecap="round"
                            stroke-linejoin="round"
                          />
                        </svg>
                        <div class="text-sm text-gray-600 dark:text-gray-300">
                          <span
                            class="font-medium text-blue-600 dark:text-blue-400"
                            >Click to upload</span
                          >
                          or drag and drop
                        </div>
                        <p class="text-xs text-gray-500 dark:text-gray-400">
                          JSON export files only
                        </p>
                      </div>
                      <input
                        type="file"
                        id="import-file-input"
                        class="hidden"
                        accept=".json,application/json"
                      />
                    </div>
                  </div>

                  <!-- Import Options -->
                  <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
                      >
                        Conflict Strategy
                      </label>
                      <select
                        id="import-conflict-strategy"
                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md text-sm bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                      >
                        <option value="update">Update existing items</option>
                        <option value="skip">Skip conflicting items</option>
                        <option value="rename">Rename conflicting items</option>
                        <option value="fail">Fail on conflicts</option>
                      </select>
                    </div>

                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
                      >
                        Options
                      </label>
                      <div class="space-y-2">
                        <label class="flex items-center">
                          <input
                            type="checkbox"
                            id="import-dry-run"
                            class="mr-2"
                          />
                          <span class="text-sm text-gray-600 dark:text-gray-300"
                            >Dry Run (validate only)</span
                          >
                        </label>
                      </div>

                      <div class="mt-2">
                        <input
                          type="text"
                          id="import-rekey-secret"
                          placeholder="New encryption secret (optional)"
                          class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md text-sm bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                        />
                        <p
                          class="text-xs text-gray-500 dark:text-gray-400 mt-1"
                        >
                          For cross-environment imports
                        </p>
                      </div>
                    </div>
                  </div>

                  <!-- Import Actions -->
                  <div class="flex space-x-4">
                    <button
                      id="import-validate-btn"
                      class="bg-yellow-600 hover:bg-yellow-700 text-white px-4 py-2 rounded-md text-sm font-medium disabled:opacity-50"
                      disabled
                    >
                      🔍 Validate Import
                    </button>
                    <button
                      id="import-execute-btn"
                      class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-md text-sm font-medium disabled:opacity-50"
                      disabled
                    >
                      ⚡ Execute Import
                    </button>
                  </div>
                </div>
              </div>

              <!-- Import Status -->
              <div id="import-status-section" class="hidden">
                <h3
                  class="text-md font-medium text-gray-900 dark:text-white mb-4"
                >
                  📊 Import Status
                </h3>

                <div class="bg-gray-50 dark:bg-gray-700 p-4 rounded-lg">
                  <div id="import-progress" class="mb-4">
                    <div
                      class="flex justify-between text-sm text-gray-600 dark:text-gray-300 mb-1"
                    >
                      <span>Progress</span>
                      <span id="import-progress-text">0%</span>
                    </div>
                    <div
                      class="w-full bg-gray-200 dark:bg-gray-600 rounded-full h-2"
                    >
                      <div
                        id="import-progress-bar"
                        class="bg-green-600 h-2 rounded-full transition-all duration-300"
                        style="width: 0%"
                      ></div>
                    </div>
                  </div>

                  <div
                    class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4 text-sm"
                  >
                    <div class="text-center">
                      <div
                        id="import-total"
                        class="text-lg font-bold text-gray-900 dark:text-white"
                      >
                        0
                      </div>
                      <div class="text-gray-600 dark:text-gray-300">Total</div>
                    </div>
                    <div class="text-center">
                      <div
                        id="import-created"
                        class="text-lg font-bold text-green-600"
                      >
                        0
                      </div>
                      <div class="text-gray-600 dark:text-gray-300">
                        Created
                      </div>
                    </div>
                    <div class="text-center">
                      <div
                        id="import-updated"
                        class="text-lg font-bold text-blue-600"
                      >
                        0
                      </div>
                      <div class="text-gray-600 dark:text-gray-300">
                        Updated
                      </div>
                    </div>
                    <div class="text-center">
                      <div
                        id="import-failed"
                        class="text-lg font-bold text-red-600"
                      >
                        0
                      </div>
                      <div class="text-gray-600 dark:text-gray-300">Failed</div>
                    </div>
                  </div>

                  <!-- Messages -->
                  <div id="import-messages" class="space-y-2">
                    <!-- Messages will be populated here -->
                  </div>
                </div>
              </div>

              <!-- Recent Imports -->
              <div class="mt-8">
                <h3
                  class="text-md font-medium text-gray-900 dark:text-white mb-4"
                >
                  📋 Recent Import Operations
                </h3>

                <div
                  class="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-600 rounded-lg"
                >
                  <div
                    id="recent-imports-list"
                    class="divide-y divide-gray-200 dark:divide-gray-600"
                  >
                    <!-- Recent imports will be loaded here -->
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- Version Info Panel -->
      <div id="version-info-panel" class="tab-panel hidden"></div>

      <!-- Catalog Panel -->
      <div id="catalog-panel" class="tab-panel">
        <div class="flex justify-between items-center mb-4">
          <div>
            <h2 class="text-2xl font-bold dark:text-gray-200">
              MCP Servers Catalog
            </h2>
            <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
              Virtual Servers let you combine Tools, Resources, and Prompts from
              the global Tools catalog into a reusable configuration.
            </p>
          </div>

          <div class="flex items-center space-x-4">
            <input
              type="text"
              data-testid="search-input"
              placeholder="Search servers..."
              class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
            />
            <div class="flex items-center">
              <input
                type="checkbox"
                id="show-inactive-servers"
                class="mr-2"
                onchange="toggleInactiveItems('servers')"
              />
              <label
                for="show-inactive-servers"
                class="text-sm font-medium text-gray-700 dark:text-gray-300"
                >Show Inactive</label
              >
            </div>
          </div>
        </div>

        <!-- Tag Filtering for Servers -->
        <div class="bg-white shadow rounded-lg p-4 mb-4 dark:bg-gray-800">
          <div class="flex items-center space-x-4">
            <label class="text-sm font-medium text-gray-700 dark:text-gray-300"
              >Filter by Tags:</label
            >
            <input
              type="text"
              id="catalog-tag-filter"
              placeholder="Enter tags (comma-separated)"
              class="flex-1 rounded-md border border-gray-300 dark:border-gray-600 shadow-sm px-3 py-1 text-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:text-gray-300"
              oninput="filterEntitiesByTags('catalog', this.value)"
            />
            <button
              onclick="clearTagFilter('catalog')"
              class="px-3 py-1 text-xs bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 rounded hover:bg-gray-300 dark:hover:bg-gray-500"
            >
              Clear
            </button>
          </div>
          <div class="mt-2">
            <span class="text-xs text-gray-500 dark:text-gray-400"
              >Available tags:</span
            >
            <div id="catalog-available-tags" class="mt-1 flex flex-wrap gap-1">
              <!-- Tag suggestions will be populated here by JavaScript -->
            </div>
          </div>
        </div>
        <div class="bg-white shadow rounded-lg p-6 mb-8 dark:bg-gray-800">
          <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
              <thead class="bg-gray-50 dark:bg-gray-700">
                <tr>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Icon
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    S. No.
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    UUID
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Name
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Description
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Tools
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Resources
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Prompts
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Tags
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody
                data-testid="server-list"
                class="bg-white divide-y divide-gray-200 dark:bg-gray-900 dark:divide-gray-700"
              >
                {% for server in servers %}
                <tr data-testid="server-item">
                  <td class="px-6 py-4 whitespace-nowrap">
                    {% if server.icon %}
                    <img
                      src="{{ server.icon }}"
                      alt="{{ server.name }} Icon"
                      class="h-8 w-8"
                    />
                    {% else %}
                    <span class="text-gray-500 dark:text-gray-300">N/A</span>
                    {% endif %}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-300"
                  >
                    {{ loop.index }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-300"
                  >
                    {{ server.id }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-300"
                  >
                    {{ server.name }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-normal break-words text-sm text-gray-500 dark:text-gray-300"
                  >
                    {{ server.description }}
                  </td>
                  <td
                    class="px-6 py-4 max-w-xs break-words text-sm text-gray-500 dark:text-gray-300"
                  >
                    {% if server.associatedTools %} {{ server.associatedTools |
                    map('string') | join(', ') }} {% else %}
                    <span class="text-gray-500 dark:text-gray-300">N/A</span>
                    {% endif %}
                  </td>
                  <td
                    class="px-6 py-4 max-w-xs break-words text-sm text-gray-500 dark:text-gray-300"
                  >
                    {% if server.associatedResources %} {{
                    server.associatedResources | join(', ') }} {% else %}
                    <span class="text-gray-500 dark:text-gray-300">N/A</span>
                    {% endif %}
                  </td>
                  <td
                    class="px-6 py-4 max-w-xs break-words text-sm text-gray-500 dark:text-gray-300"
                  >
                    {% if server.associatedPrompts %} {{
                    server.associatedPrompts | join(', ') }} {% else %}
                    <span class="text-gray-500 dark:text-gray-300">N/A</span>
                    {% endif %}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    {% if server.tags %} {% for tag in server.tags %}
                    <span
                      class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800 mr-1 mb-1"
                      >{{ tag }}</span
                    >
                    {% endfor %} {% else %}
                    <span class="text-gray-500 dark:text-gray-300 text-xs"
                      >None</span
                    >
                    {% endif %}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    {% if server.isActive %}
                    <form
                      method="POST"
                      action="{{ root_path }}/admin/servers/{{ server.id }}/toggle"
                      class="inline mr-2"
                      onsubmit="return handleToggleSubmit(event, 'servers')"
                    >
                      <input type="hidden" name="activate" value="false" />
                      <button
                        type="submit"
                        x-tooltip="'💡Temporarily disable this item (can be re-activated).'"
                        class="text-yellow-600 hover:text-yellow-900"
                      >
                        Deactivate
                      </button>
                    </form>
                    {% else %}
                    <form
                      method="POST"
                      action="{{ root_path }}/admin/servers/{{ server.id }}/toggle"
                      class="inline mr-2"
                      onsubmit="return handleToggleSubmit(event, 'servers')"
                    >
                      <input type="hidden" name="activate" value="true" />
                      <button
                        type="submit"
                        x-tooltip="'💡Re-enable an inactive item.'"
                        class="text-blue-600 hover:text-blue-900"
                      >
                        Activate
                      </button>
                    </form>
                    {% endif %}
                    <button
                      onclick="viewServer('{{ server.id }}')"
                      class="text-indigo-600 dark:text-indigo-500 hover:text-indigo-900 mr-2"
                    >
                      View
                    </button>
                    <button
                      onclick="editServer('{{ server.id }}')"
                      class="text-green-600 hover:text-green-900 mr-2"
                    >
                      Edit
                    </button>
                    <!-- Export Config Button -->
                    <button
                      onclick="showConfigSelectionModal('{{ server.id }}', '{{ server.name }}')"
                      class="text-purple-600 hover:text-purple-900 mr-2"
                      x-tooltip="'💡Generate client configuration files for this server'"
                    >
                      Export Config
                    </button>
                    <form
                      method="POST"
                      action="{{ root_path }}/admin/servers/{{ server.id }}/delete"
                      class="inline"
                      onsubmit="return handleSubmitWithConfirmation(event, 'servers')"
                    >
                      <button
                        type="submit"
                        x-tooltip="'💡Permanently delete this item – cannot be undone.'"
                        class="text-red-600 hover:text-red-900"
                      >
                        Delete
                      </button>
                    </form>
                  </td>
                </tr>
                {% endfor %}
              </tbody>
            </table>
          </div>
        </div>
        <div class="bg-white shadow rounded-lg p-6 dark:bg-gray-800">
          <h3 class="text-lg font-bold mb-4 dark:text-gray-200">
            Add New Server
          </h3>
          <form
            method="POST"
            id="add-server-form"
            onreset="document.getElementById('associatedTools').selectedIndex = -1;"
          >
            <div class="grid grid-cols-1 gap-6">
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Custom UUID (optional)</label
                >
                <input
                  type="text"
                  name="id"
                  placeholder="Leave blank to auto-generate"
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
                <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
                  Provide a custom UUID if you need to preserve an existing server ID
                </p>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Name</label
                >
                <input
                  type="text"
                  name="name"
                  required
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Description</label
                >
                <textarea
                  name="description"
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                ></textarea>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Icon URL</label
                >
                <input
                  type="url"
                  name="icon"
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
              </div>
              <div
                class="p-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-300 dark:border-gray-700"
              >
                <label
                  class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2"
                  for="associatedTools"
                >
                  Associated Tools
                </label>
                <input
                  type="text"
                  id="searchTools"
                  placeholder="Search for tools..."
                  class="mb-4 block w-full rounded-md border-gray-300 dark:border-gray-600 shadow-sm p-2 dark:bg-gray-900 dark:text-gray-300"
                />
                <div
                  id="associatedTools"
                  class="max-h-60 overflow-y-auto rounded-md border border-gray-300 dark:border-gray-700 shadow-sm p-3 bg-gray-50 dark:bg-gray-900"
                >
                  {% for tool in tools %}
                  <label
                    class="flex items-center space-x-3 text-gray-700 dark:text-gray-300 mb-2 cursor-pointer hover:bg-indigo-50 dark:hover:bg-indigo-900 rounded-md p-1 tool-item"
                  >
                    <input
                      type="checkbox"
                      name="associatedTools"
                      value="{{ tool.id }}"
                      class="tool-checkbox form-checkbox h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                    />
                    <span class="select-none">{{ tool.displayName or tool.customName or tool.name }}</span>
                  </label>
                  {% endfor %}
                  <p
                    id="noToolsMessage"
                    class="text-gray-700 dark:text-gray-300"
                    style="display: none"
                  >
                    No tool found containing "<span id="searchQuery"></span>"
                  </p>
                </div>
                <div class="flex justify-end mt-3 gap-2">
                  <button
                    type="button"
                    id="selectAllToolsBtn"
                    class="px-3 py-1 text-sm font-semibold text-green-600 border border-green-600 rounded-md hover:bg-green-50 focus:outline-none focus:ring-2 focus:ring-green-300 focus:ring-offset-1"
                    aria-label="Select all tools"
                  >
                    Select All
                  </button>

                  <button
                    type="button"
                    id="clearAllToolsBtn"
                    class="px-3 py-1 text-sm font-semibold text-red-600 border border-red-600 rounded-md hover:bg-red-50 focus:outline-none focus:ring-2 focus:ring-red-300 focus:ring-offset-1"
                    aria-label="Clear all selected tools"
                  >
                    Clear All
                  </button>
                </div>

                <!-- Selected pills -->
                <div
                  id="selectedToolsPills"
                  class="mt-4 flex flex-wrap gap-2"
                ></div>

                <!-- Warning message -->
                <div
                  id="selectedToolsWarning"
                  class="mt-2 min-h-[1.25rem] text-sm font-semibold text-yellow-600"
                  aria-live="polite"
                ></div>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Associated Resources (comma-separated IDs)</label
                >
                <input
                  type="text"
                  name="associatedResources"
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  placeholder="e.g., resource1, resource2"
                />
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Associated Prompts (comma-separated IDs)</label
                >
                <input
                  type="text"
                  name="associatedPrompts"
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  placeholder="e.g., prompt1, prompt2"
                />
              </div>
            </div>
            <!-- 🔻 Error Display Span -->
            <span
              id="serverFormError"
              class="block text-sm font-semibold text-red-600 mt-2"
            ></span>

            <!-- 🔄 Optional Loading Indicator -->
            <div
              id="add-server-loading"
              class="hidden text-sm text-gray-500 mt-2"
            >
              Submitting...
            </div>

            <div>
              <label
                class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                >Tags</label
              >
              <input
                type="text"
                name="tags"
                placeholder="e.g., development,production,api-gateway (comma-separated)"
                class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
              />
              <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                Enter tags separated by commas. Tags help categorize and filter
                servers.
              </p>
            </div>

            <div class="mt-6">
              <button
                type="submit"
                x-tooltip="'💡Creates a new Virtual Server by combining Tools, Resources & Prompts from global catalogs.'"
                class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
              >
                Add Server
              </button>
            </div>
          </form>
        </div>
      </div>

      <!-- Tools Panel -->
      <div id="tools-panel" class="tab-panel hidden">
        <div class="flex justify-between items-center mb-4">
          <div>
            <h2 class="text-2xl font-bold dark:text-gray-200">
              Registered Tools
            </h2>
            <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
              This is the global catalog of Tools available. Create a Virtual
              Server using one of these tools.
            </p>
            <div class="mt-2 text-xs text-gray-500 dark:text-gray-400">
              <strong>Annotation badges:</strong>
              <span
                class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800 ml-1"
                >📖 Read-Only</span
              >
              <span
                class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-red-100 text-red-800 ml-1"
                >⚠️ Destructive</span
              >
              <span
                class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-purple-100 text-purple-800 ml-1"
                >🔄 Idempotent</span
              >
              <span
                class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-yellow-100 text-yellow-800 ml-1"
                >🌐 External Access</span
              >
            </div>
          </div>
          <div class="flex items-center space-x-4">
            <input
              type="checkbox"
              id="show-inactive-tools"
              class="mr-2"
              onchange="toggleInactiveItems('tools')"
            />
            <label
              for="show-inactive-tools"
              class="text-sm font-medium text-gray-700 dark:text-gray-300"
              >Show Inactive</label
            >
          </div>
        </div>

        <!-- Tag Filtering for Tools -->
        <div class="bg-white shadow rounded-lg p-4 mb-4 dark:bg-gray-800">
          <div class="flex items-center space-x-4">
            <label class="text-sm font-medium text-gray-700 dark:text-gray-300"
              >Filter by Tags:</label
            >
            <input
              type="text"
              id="tools-tag-filter"
              placeholder="Enter tags (comma-separated)"
              class="flex-1 rounded-md border border-gray-300 dark:border-gray-600 shadow-sm px-3 py-1 text-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:text-gray-300"
              oninput="filterEntitiesByTags('tools', this.value)"
            />
            <button
              onclick="clearTagFilter('tools')"
              class="px-3 py-1 text-xs bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 rounded hover:bg-gray-300 dark:hover:bg-gray-500"
            >
              Clear
            </button>
          </div>
          <div class="mt-2">
            <span class="text-xs text-gray-500 dark:text-gray-400"
              >Available tags:</span
            >
            <div id="tools-available-tags" class="mt-1 flex flex-wrap gap-1">
              <!-- Tag suggestions will be populated here by JavaScript -->
            </div>
          </div>
        </div>
        <div class="bg-white shadow rounded-lg p-6 mb-8 dark:bg-gray-800">
          <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
              <thead class="bg-gray-50 dark:bg-gray-700">
                <tr>
                  <th
                    class="px-2 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider w-12"
                  >
                    S. No.
                  </th>
                  <th
                    class="px-2 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider w-36"
                  >
                    Gateway Name
                  </th>

                  <th
                    class="px-2 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider w-24"
                  >
                    Name
                  </th>
                  <th
                    class="px-2 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider w-24"
                  >
                    URL
                  </th>
                  <th
                    class="px-2 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider w-12"
                  >
                    Type
                  </th>
                  <th
                    class="px-2 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider w-12"
                  >
                    Request Type
                  </th>
                  <th
                    class="px-2 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Description
                  </th>
                  <th
                    class="px-2 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider w-24"
                  >
                    Annotations
                  </th>
                  <th
                    class="px-2 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider w-20"
                  >
                    Tags
                  </th>
                  <th
                    class="px-2 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider w-12"
                  >
                    Status
                  </th>
                  <th
                    class="px-2 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider w-32"
                  >
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody
                class="bg-white divide-y divide-gray-200 dark:bg-gray-900 dark:divide-gray-700"
              >
                {% for tool in tools %}
                <tr>
                  <td
                    class="px-2 py-4 whitespace-nowrap text-sm font-medium text-gray-900 w-12 dark:text-gray-100"
                  >
                    {{ loop.index }}
                  </td>
                  <td
                    class="px-2 py-4 whitespace-normal break-words text-sm text-gray-500 dark:text-gray-300 w-36"
                  >
                    {{ tool.gatewaySlug }}
                  </td>
                  <td
                    class="px-2 py-4 whitespace-nowrap text-sm font-medium text-gray-900 w-24 dark:text-gray-100"
                  >
                    {{ tool.name }}
                  </td>
                  <td
                    class="px-2 py-4 whitespace-normal break-words text-sm text-gray-500 dark:text-gray-300 w-24"
                  >
                    {{ tool.url }}
                  </td>
                  <td
                    class="px-2 py-4 whitespace-normal break-words text-sm text-gray-500 dark:text-gray-300 w-12"
                  >
                    {{ tool.integrationType }}
                  </td>
                  <td
                    class="px-2 py-4 whitespace-normal break-words text-sm text-gray-500 dark:text-gray-300 w-12"
                  >
                    {{ tool.requestType }}
                  </td>
                  <td
                    class="px-2 py-4 whitespace-normal break-words text-sm text-gray-500 dark:text-gray-300"
                  >
                    {% set clean_desc = (tool.description or "") | replace('\n',
                    ' ') | replace('\r', ' ') %} {% set refactor_desc =
                    clean_desc | striptags | trim | escape %} {% if
                    refactor_desc | length is greaterthan 120 %} {{
                    refactor_desc[:120] }}... {% else %} {{ refactor_desc }} {%
                    endif %}
                  </td>
                  <td class="px-2 py-4 whitespace-nowrap">
                    {% if tool.annotations %} {% if tool.annotations.title %}
                    <span
                      class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800 mr-1 mb-1"
                      >{{ tool.annotations.title }}</span
                    >
                    {% endif %} {% if tool.annotations.readOnlyHint %}
                    <span
                      class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800 mr-1 mb-1"
                      >📖</span
                    >
                    {% endif %} {% if tool.annotations.destructiveHint %}
                    <span
                      class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-red-100 text-red-800 mr-1 mb-1"
                      >⚠️</span
                    >
                    {% endif %} {% if tool.annotations.idempotentHint %}
                    <span
                      class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-purple-100 text-purple-800 mr-1 mb-1"
                      >🔄</span
                    >
                    {% endif %} {% if tool.annotations.openWorldHint %}
                    <span
                      class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-yellow-100 text-yellow-800 mr-1 mb-1"
                      >🌐</span
                    >
                    {% endif %} {% else %}
                    <span class="text-gray-500 dark:text-gray-300 text-xs"
                      >None</span
                    >
                    {% endif %}
                  </td>
                  <td class="px-2 py-4 whitespace-nowrap">
                    {% if tool.tags %} {% for tag in tool.tags %}
                    <span
                      class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800 mr-1 mb-1"
                      >{{ tag }}</span
                    >
                    {% endfor %} {% else %}
                    <span class="text-gray-500 dark:text-gray-300 text-xs"
                      >None</span
                    >
                    {% endif %}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    {% set enabled = tool.enabled %} {% set reachable =
                    tool.reachable %} {% if enabled and reachable %} {% set
                    bg_class = "bg-green-100 text-green-800" %} {% elif enabled
                    and not reachable %} {% set bg_class = "bg-yellow-100
                    text-yellow-800" %} {% else %} {% set bg_class = "bg-red-100
                    text-red-800" %} {% endif %}
                    <div class="relative group inline-block">
                      <span
                        class="px-2 inline-flex items-center text-xs leading-5 font-semibold rounded-full {{ bg_class }}"
                      >
                        {% if enabled %} {% if reachable %}
                        <!-- Active label with green check -->
                        Active
                        <svg
                          class="ml-1 h-4 w-4 text-green-600"
                          fill="currentColor"
                          viewBox="0 0 20 20"
                        >
                          <path
                            fill-rule="evenodd"
                            d="M10 18a8 8 0 100-16 8 8 0 000 16zm-1-4.586l5.293-5.293-1.414-1.414L9 11.586 7.121 9.707 5.707 11.121 9 14.414z"
                            clip-rule="evenodd"
                          />
                        </svg>
                        {% else %}
                        <!-- Offline label with yellow warning -->
                        Offline
                        <svg
                          class="ml-1 h-4 w-4 text-yellow-600"
                          fill="currentColor"
                          viewBox="0 0 20 20"
                        >
                          <path
                            fill-rule="evenodd"
                            d="M10 18a8 8 0 100-16 8 8 0 000 16zm-1-10h2v4h-2V8zm0 6h2v2h-2v-2z"
                            clip-rule="evenodd"
                          />
                        </svg>
                        {% endif %} {% else %}
                        <!-- Inactive label with red cross -->
                        Inactive
                        <svg
                          class="ml-1 h-4 w-4 text-red-600"
                          fill="currentColor"
                          viewBox="0 0 20 20"
                        >
                          <path
                            fill-rule="evenodd"
                            d="M6.293 6.293a1 1 0 011.414 0L10 8.586l2.293-2.293a1 1 0 111.414 1.414L11.414 10l2.293 2.293a1 1 0 11-1.414 1.414L10 11.414l-2.293 2.293a1 1 0 11-1.414-1.414L8.586 10 6.293 7.707a1 1 0 010-1.414z"
                            clip-rule="evenodd"
                          />
                        </svg>
                        {% endif %}
                      </span>
                      <div
                        class="absolute left-full top-1/2 -translate-y-1/2 ml-2 hidden group-hover:block bg-gray-800 text-white text-xs rounded py-1 px-2 z-10 whitespace-nowrap shadow"
                      >
                        {% if not enabled %} 💡Tool is Manually Deactivated. {%
                        elif not reachable %} 💡The host gateway for this tool
                        is unreachable. {% else %} 💡Everything stable. {% endif
                        %}
                      </div>
                    </div>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <button
                      onclick="testTool('{{ tool.id }}')"
                      class="text-purple-600 hover:text-purple-900 mr-2"
                      x-tooltip="'💡Execute this Tool with sample inputs.'"
                    >
                      Test
                    </button>
                    {% if tool.enabled %}
                    <form
                      method="POST"
                      action="{{ root_path }}/admin/tools/{{ tool.id }}/toggle"
                      class="inline mr-2"
                      onsubmit="return handleToggleSubmit(event, 'tools')"
                    >
                      <input type="hidden" name="activate" value="false" />
                      <button
                        type="submit"
                        x-tooltip="'💡Temporarily disable this item (can be re-activated).'"
                        class="text-yellow-600 hover:text-yellow-900"
                      >
                        Deactivate
                      </button>
                    </form>
                    {% else %}
                    <form
                      method="POST"
                      action="{{ root_path }}/admin/tools/{{ tool.id }}/toggle"
                      class="inline mr-2"
                      onsubmit="return handleToggleSubmit(event, 'tools')"
                    >
                      <input type="hidden" name="activate" value="true" />
                      <button
                        type="submit"
                        x-tooltip="'💡Re-enable an inactive item.'"
                        class="text-blue-600 hover:text-blue-900"
                      >
                        Activate
                      </button>
                    </form>
                    {% endif %}
                    <button
                      onclick="viewTool('{{ tool.id }}')"
                      class="text-red-600 dark:text-indigo-500 hover:text-indigo-900 mr-2"
                    >
                      View
                    </button>
                    <button
                      onclick="editTool('{{ tool.id }}')"
                      class="text-green-600 hover:text-green-900 mr-2"
                    >
                      Edit
                    </button>
                    <form
                      method="POST"
                      action="{{ root_path }}/admin/tools/{{ tool.id }}/delete"
                      class="inline"
                      onsubmit="return handleSubmitWithConfirmation(event, 'tools')"
                    >
                      <button
                        type="submit"
                        x-tooltip="'💡Permanently delete this item – cannot be undone.'"
                        class="text-red-600 hover:text-red-900"
                      >
                        Delete
                      </button>
                    </form>
                  </td>
                </tr>
                {% endfor %}
              </tbody>
            </table>
          </div>
        </div>
        <div class="bg-white shadow rounded-lg p-6 dark:bg-gray-800">
          <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-bold dark:text-gray-200">Add New Tool</h3>

            <!-- Bulk Import Dropdown -->
            <div class="relative">
              <button
                id="bulk-import-dropdown-btn"
                onclick="toggleBulkImportDropdown()"
                class="inline-flex items-center px-3 py-2 border border-gray-300 dark:border-gray-600 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
              >
                <svg
                  class="w-4 h-4 mr-2 text-green-600"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"
                  ></path>
                </svg>
                Bulk Import
                <svg
                  class="w-4 h-4 ml-1"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M19 9l-7 7-7-7"
                  ></path>
                </svg>
              </button>

              <!-- Dropdown Menu -->
              <div
                id="bulk-import-dropdown"
                class="hidden absolute right-0 mt-2 w-96 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-600 rounded-lg shadow-lg z-50"
              >
                <div class="p-4">
                  <!-- Information Section -->
                  <div class="mb-4">
                    <h4
                      class="text-sm font-semibold text-gray-900 dark:text-gray-100 mb-2"
                    >
                      📥 Bulk Import Information
                    </h4>
                    <div
                      class="text-xs text-gray-600 dark:text-gray-400 space-y-1"
                    >
                      <p>
                        Import multiple tools from a JSON array. The system
                        automatically fixes common formatting issues like tool
                        name spaces and tag formats.
                      </p>
                      <p><strong>Maximum:</strong> 200 tools per import</p>
                    </div>
                  </div>

                  <!-- Import Method Selection -->
                  <div class="mb-4">
                    <h5
                      class="text-xs font-medium text-gray-700 dark:text-gray-300 mb-2"
                    >
                      Choose Import Method:
                    </h5>
                    <div class="flex space-x-4">
                      <label class="flex items-center">
                        <input
                          type="radio"
                          name="dropdown-import-method"
                          value="file"
                          checked
                          onchange="toggleDropdownImportMethod('file')"
                          class="mr-2"
                        />
                        <span class="text-xs text-gray-600 dark:text-gray-400"
                          >Upload File</span
                        >
                      </label>
                      <label class="flex items-center">
                        <input
                          type="radio"
                          name="dropdown-import-method"
                          value="paste"
                          onchange="toggleDropdownImportMethod('paste')"
                          class="mr-2"
                        />
                        <span class="text-xs text-gray-600 dark:text-gray-400"
                          >Paste JSON</span
                        >
                      </label>
                    </div>
                  </div>

                  <!-- File Upload Section -->
                  <div id="dropdown-file-section" class="mb-4">
                    <label
                      class="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-2"
                    >
                      Upload JSON File
                    </label>
                    <div
                      class="border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg p-3 text-center"
                    >
                      <input
                        type="file"
                        id="dropdown-file-input"
                        accept=".json"
                        onchange="handleDropdownFileSelect(this)"
                        class="hidden"
                      />
                      <div
                        id="dropdown-file-drop-zone"
                        onclick="document.getElementById('dropdown-file-input').click()"
                        class="cursor-pointer"
                      >
                        <svg
                          class="mx-auto h-8 w-8 text-gray-400"
                          fill="none"
                          stroke="currentColor"
                          viewBox="0 0 24 24"
                        >
                          <path
                            stroke-linecap="round"
                            stroke-linejoin="round"
                            stroke-width="2"
                            d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"
                          ></path>
                        </svg>
                        <p
                          class="text-xs text-gray-500 dark:text-gray-400 mt-1"
                        >
                          Click to upload JSON file
                        </p>
                      </div>
                      <div
                        id="dropdown-file-info"
                        class="hidden mt-2 text-xs text-green-600 dark:text-green-400"
                      ></div>
                    </div>
                  </div>

                  <!-- JSON Paste Section -->
                  <div id="dropdown-paste-section" class="hidden mb-4">
                    <label
                      class="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-2"
                    >
                      Paste JSON Data
                    </label>
                    <textarea
                      id="dropdown-json-textarea"
                      rows="6"
                      placeholder="[{&quot;name&quot;: &quot;example_tool&quot;, &quot;url&quot;: &quot;https://api.example.com&quot;, &quot;description&quot;: &quot;Example tool&quot;}]"
                      oninput="validateDropdownJson()"
                      class="w-full text-xs border border-gray-300 dark:border-gray-600 rounded-md p-2 dark:bg-gray-700 dark:text-gray-300"
                    ></textarea>
                    <div id="dropdown-json-status" class="mt-1 text-xs"></div>
                  </div>

                  <!-- Preview Section -->
                  <div id="dropdown-preview" class="hidden mb-4">
                    <h5
                      class="text-xs font-medium text-gray-700 dark:text-gray-300 mb-2"
                    >
                      Import Preview
                    </h5>
                    <div class="bg-gray-50 dark:bg-gray-700 rounded-md p-2">
                      <div class="text-xs text-gray-600 dark:text-gray-400">
                        <span id="dropdown-preview-count">0</span> tools ready
                        for import
                      </div>
                    </div>
                  </div>

                  <!-- Status Messages -->
                  <div id="dropdown-status" class="hidden mb-4 text-xs"></div>

                  <!-- Action Buttons -->
                  <div class="flex justify-between items-center">
                    <button
                      onclick="resetDropdownImport()"
                      class="text-xs text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
                    >
                      Clear
                    </button>
                    <div class="space-x-2">
                      <button
                        onclick="toggleBulkImportDropdown()"
                        class="px-3 py-1 text-xs border border-gray-300 dark:border-gray-600 rounded text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-600"
                      >
                        Cancel
                      </button>
                      <button
                        id="dropdown-import-btn"
                        onclick="submitDropdownImport()"
                        disabled
                        class="px-3 py-1 text-xs bg-green-600 text-white rounded hover:bg-green-700 disabled:bg-gray-400 disabled:cursor-not-allowed"
                      >
                        Import Tools
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <form id="add-tool-form">
            <div class="grid grid-cols-1 gap-6">
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Name</label
                >
                <input
                  type="text"
                  name="name"
                  required
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
              </div>

              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Display Name (optional)</label
                >
                <input
                  type="text"
                  name="displayName"
                  placeholder="Custom display name for your UI"
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
              </div>

              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >URL</label
                >
                <input
                  type="url"
                  name="url"
                  required
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Description</label
                >
                <textarea
                  name="description"
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                ></textarea>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Integration Type</label
                >
                <select
                  id="integrationType"
                  name="integrationType"
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  onchange="updateRequestTypeOptions()"
                >
                  <option value="REST">REST</option>
                </select>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Request Type</label
                >
                <select
                  id="requestType"
                  name="requestType"
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                >
                  <!-- options will be filled by JS -->
                </select>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Headers (JSON)</label
                >
                <textarea
                  name="headers"
                  id="headers-editor"
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                ></textarea>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Input Schema (JSON)</label
                >
                <div class="mb-2">
                  <label class="mr-4 dark:text-gray-300">
                    <input
                      type="radio"
                      name="schema_input_mode"
                      value="ui"
                      checked
                    />
                    Schema Builder
                  </label>
                  <label class="dark:text-gray-300">
                    <input type="radio" name="schema_input_mode" value="json" />
                    JSON Input
                  </label>
                </div>
                <div id="ui-builder" class="border p-4 mb-4">
                  <div id="parameters-container"></div>
                  <button
                    type="button"
                    id="add-parameter-btn"
                    class="mt-2 inline-flex justify-center py-1 px-2 border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-green-600 hover:bg-green-700"
                  >
                    Add New Parameter
                  </button>
                </div>
                <div id="json-input-container" style="display: none">
                  <textarea
                    name="input_schema"
                    id="schema-editor"
                    class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  ></textarea>
                </div>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Json Path Filter</label
                >
                <input
                  type="text"
                  name="jsonpath_filter"
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
              </div>
              <!-- Authentication Section -->
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Authentication Type</label
                >
                <select
                  name="auth_type"
                  id="auth-type"
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                >
                  <option value="">None</option>
                  <option value="basic">Basic</option>
                  <option value="bearer">Bearer Token</option>
                  <option value="authheaders">Custom Headers</option>
                </select>
              </div>
              <div id="auth-basic-fields" style="display: none">
                <div>
                  <label class="block text-sm font-medium text-gray-700"
                    >Username</label
                  >
                  <input
                    type="text"
                    name="auth_username"
                    class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  />
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700"
                    >Password</label
                  >
                  <input
                    type="password"
                    name="auth_password"
                    class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  />
                </div>
              </div>
              <div id="auth-bearer-fields" style="display: none">
                <div>
                  <label class="block text-sm font-medium text-gray-700"
                    >Token</label
                  >
                  <input
                    type="password"
                    name="auth_token"
                    class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  />
                </div>
              </div>
              <div id="auth-headers-fields" style="display: none">
                <div class="space-y-3">
                  <div class="flex items-center justify-between">
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >
                      Custom Headers
                    </label>
                    <button
                      type="button"
                      onclick="addAuthHeader('auth-headers-container')"
                      class="inline-flex items-center px-3 py-1 border border-transparent text-sm leading-4 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                    >
                      <svg
                        class="w-4 h-4 mr-1"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          stroke-linecap="round"
                          stroke-linejoin="round"
                          stroke-width="2"
                          d="M12 6v6m0 0v6m0-6h6m-6 0H6"
                        ></path>
                      </svg>
                      Add Header
                    </button>
                  </div>
                  <div id="auth-headers-container" class="space-y-2">
                    <!-- Headers will be added dynamically here -->
                  </div>
                  <input
                    type="hidden"
                    name="auth_headers"
                    id="auth-headers-json"
                  />
                </div>
              </div>
            </div>
            <div>
              <label
                class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                >Tags</label
              >
              <input
                type="text"
                name="tags"
                placeholder="e.g., api,data-processing,external (comma-separated)"
                class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
              />
              <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                Enter tags separated by commas. Tags help categorize and filter
                tools.
              </p>
            </div>
            <div class="mt-6">
              <button
                type="submit"
                x-tooltip="'💡  Registers a new Tool from an existing REST endpoint. Use Gateways to add MCP servers.'"
                class="inline-flex justify-center py-2 px-4 border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
              >
                Add Tool
              </button>
            </div>
          </form>
        </div>
      </div>

      <!-- Bulk Import Modal -->
      <div id="bulk-import-modal" class="fixed inset-0 z-[60] hidden">
        <div
          id="bulk-import-backdrop"
          class="absolute inset-0 bg-black/50"
        ></div>
        <div
          role="dialog"
          aria-modal="true"
          class="relative mx-auto my-12 w-full max-w-2xl rounded-xl bg-white p-0 shadow-xl dark:bg-gray-900"
        >
          <div
            class="flex items-center justify-between border-b px-5 py-3 dark:border-gray-700"
          >
            <h3 class="text-base font-semibold dark:text-gray-100">
              Bulk Import Tools
            </h3>
            <button
              id="close-bulk-import"
              data-close-bulk-import
              class="rounded p-1 text-gray-500 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-800"
              aria-label="Close"
            >
              ✕
            </button>
          </div>

          <form
            id="bulk-import-form"
            enctype="multipart/form-data"
            class="space-y-4 p-5"
          >
            <p class="text-sm text-gray-600 dark:text-gray-400">
              Paste a JSON array or upload a <code>.json</code> file. Max {{
              bulk_import_max_tools }} tools.
            </p>

            <label
              class="block text-sm font-medium dark:text-gray-300"
              for="tools_json"
              >JSON Data</label
            >
            <textarea
              id="tools_json"
              name="tools_json"
              rows="8"
              class="mt-1 block w-full rounded-md border border-gray-300 font-mono text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300"
              placeholder="[{&quot;name&quot;:&quot;tool_name&quot;,&quot;url&quot;:&quot;https://...&quot;,&quot;integration_type&quot;:&quot;REST&quot;,&quot;request_type&quot;:&quot;GET&quot;}]"
            ></textarea>

            <div>
              <label
                class="block text-sm font-medium dark:text-gray-300"
                for="tools_file"
                >Or upload JSON file</label
              >
              <input
                id="tools_file"
                name="tools_file"
                type="file"
                accept="application/json,.json"
                class="mt-1 block w-full text-sm dark:text-gray-300"
              />
            </div>

            <div class="flex items-center gap-3 pt-1">
              <button
                type="submit"
                class="inline-flex justify-center rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500"
              >
                Import Tools
              </button>
              <span
                id="bulk-import-indicator"
                class="htmx-indicator flex items-center text-sm text-gray-500 dark:text-gray-400"
              >
                <svg
                  class="mr-2 h-4 w-4 animate-spin"
                  viewBox="0 0 24 24"
                  fill="none"
                >
                  <circle
                    class="opacity-25"
                    cx="12"
                    cy="12"
                    r="10"
                    stroke="currentColor"
                    stroke-width="4"
                  />
                  <path
                    class="opacity-75"
                    fill="currentColor"
                    d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
                  />
                </svg>
                Processing...
              </span>
            </div>

            <div id="import-result" class="pt-2"></div>
          </form>
        </div>
      </div>

      <!-- Resources Panel -->
      <div id="resources-panel" class="tab-panel hidden">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-2xl font-bold dark:text-gray-200">
            Available Resources
          </h2>
          <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
            Resources are reusable data assets-like text, code, or media-that
            Tools and Prompts can reference by URI.
          </p>
          <div class="flex items-center">
            <input
              type="checkbox"
              id="show-inactive-resources"
              class="mr-2"
              onchange="toggleInactiveItems('resources')"
            />
            <label
              for="show-inactive-resources"
              class="text-sm font-medium text-gray-700 dark:text-gray-300"
              >Show Inactive</label
            >
          </div>
        </div>

        <!-- Tag Filtering for Resources -->
        <div class="bg-white shadow rounded-lg p-4 mb-4 dark:bg-gray-800">
          <div class="flex items-center space-x-4">
            <label class="text-sm font-medium text-gray-700 dark:text-gray-300"
              >Filter by Tags:</label
            >
            <input
              type="text"
              id="resources-tag-filter"
              placeholder="Enter tags (comma-separated)"
              class="flex-1 rounded-md border border-gray-300 dark:border-gray-600 shadow-sm px-3 py-1 text-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:text-gray-300"
              oninput="filterEntitiesByTags('resources', this.value)"
            />
            <button
              onclick="clearTagFilter('resources')"
              class="px-3 py-1 text-xs bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 rounded hover:bg-gray-300 dark:hover:bg-gray-500"
            >
              Clear
            </button>
          </div>
          <div class="mt-2">
            <span class="text-xs text-gray-500 dark:text-gray-400"
              >Available tags:</span
            >
            <div
              id="resources-available-tags"
              class="mt-1 flex flex-wrap gap-1"
            >
              <!-- Tag suggestions will be populated here by JavaScript -->
            </div>
          </div>
        </div>
        <div class="bg-white shadow rounded-lg p-6 mb-8 dark:bg-gray-800">
          <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
              <thead class="bg-gray-50 dark:bg-gray-700">
                <tr>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    ID
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    URI
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Name
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Description
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    MIME Type
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Tags
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Status
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody
                class="bg-white divide-y divide-gray-200 dark:bg-gray-900 dark:divide-gray-700"
              >
                {% for resource in resources %}
                <tr>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100"
                  >
                    {{ resource.id }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-normal break-words text-sm font-medium text-gray-900 dark:text-gray-100"
                  >
                    {{ resource.uri }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-normal break-words text-sm font-medium text-gray-900 dark:text-gray-100"
                  >
                    {{ resource.name }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-normal break-words text-sm font-medium text-gray-900 dark:text-gray-100"
                  >
                    {{ resource.description or "N/A" }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-500"
                  >
                    {{ resource.mimeType or "N/A" }}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    {% if resource.tags %} {% for tag in resource.tags %}
                    <span
                      class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800 mr-1 mb-1"
                      >{{ tag }}</span
                    >
                    {% endfor %} {% else %}
                    <span class="text-gray-500 dark:text-gray-300 text-xs"
                      >None</span
                    >
                    {% endif %}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    <span
                      class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full {% if resource.isActive %}bg-green-100 text-green-800{% else %}bg-red-100 text-red-800{% endif %}"
                    >
                      {{ "Active" if resource.isActive else "Inactive" }}
                    </span>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    {% if resource.isActive %}
                    <form
                      method="POST"
                      action="{{ root_path }}/admin/resources/{{ resource.id }}/toggle"
                      class="inline mr-2"
                      onsubmit="return handleToggleSubmit(event, 'resources')"
                    >
                      <input type="hidden" name="activate" value="false" />
                      <button
                        type="submit"
                        x-tooltip="'💡Temporarily disable this item (can be re-activated).'"
                        class="text-yellow-600 hover:text-yellow-900"
                      >
                        Deactivate
                      </button>
                    </form>
                    {% else %}
                    <form
                      method="POST"
                      action="{{ root_path }}/admin/resources/{{ resource.id }}/toggle"
                      class="inline mr-2"
                      onsubmit="return handleToggleSubmit(event, 'resources')"
                    >
                      <input type="hidden" name="activate" value="true" />
                      <button
                        type="submit"
                        x-tooltip="'💡Re-enable an inactive item.'"
                        class="text-blue-600 hover:text-blue-900"
                      >
                        Activate
                      </button>
                    </form>
                    {% endif %}
                    <button
                      onclick="viewResource('{{ resource.uri }}')"
                      class="text-indigo-600 dark:text-indigo-500 hover:text-indigo-900 mr-2"
                    >
                      View
                    </button>
                    <button
                      onclick="editResource('{{ resource.uri }}')"
                      class="text-green-600 hover:text-green-900 mr-2"
                    >
                      Edit
                    </button>
                    <form
                      method="POST"
                      action="{{ root_path }}/admin/resources/{{ resource.uri }}/delete"
                      class="inline"
                      onsubmit="return handleSubmitWithConfirmation(event, 'resources')"
                    >
                      <button
                        type="submit"
                        x-tooltip="'💡Permanently delete this item – cannot be undone.'"
                        class="text-red-600 hover:text-red-900"
                      >
                        Delete
                      </button>
                    </form>
                  </td>
                </tr>
                {% endfor %}
              </tbody>
            </table>
          </div>
        </div>

        <div class="bg-white shadow rounded-lg p-6 dark:bg-gray-800">
          <h3 class="text-lg font-bold mb-4 dark:text-gray-200">
            Add New Resource
          </h3>
          <form id="add-resource-form">
            <div class="grid grid-cols-1 gap-6">
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >URI</label
                >
                <input
                  type="text"
                  name="uri"
                  required
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Name</label
                >
                <input
                  type="text"
                  name="name"
                  required
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Description</label
                >
                <textarea
                  name="description"
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                ></textarea>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >MIME Type</label
                >
                <input
                  type="text"
                  name="mimeType"
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  placeholder="text/plain"
                />
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Content</label
                >
                <textarea
                  name="content"
                  id="resource-content-editor"
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  placeholder=""
                ></textarea>
              </div>
              <div id="add-resources-loading" style="display: none">
                <div class="spinner"></div>
              </div>
              <div id="status-resources"></div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Tags</label
                >
                <input
                  type="text"
                  name="tags"
                  placeholder="e.g., documentation,api-spec,template (comma-separated)"
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
                <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                  Enter tags separated by commas. Tags help categorize and
                  filter resources.
                </p>
              </div>
            </div>
            <div class="mt-6">
              <button
                type="submit"
                x-tooltip="'💡Uploads or links a reusable data asset (file, URI, or text).'"
                class="inline-flex justify-center py-2 px-4 border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
              >
                Add Resource
              </button>
            </div>
          </form>
        </div>
      </div>

      <!-- Prompts Panel -->
      <div id="prompts-panel" class="tab-panel hidden">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-2xl font-bold dark:text-gray-200">
            Available Prompts
          </h2>
          <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
            Prompts define reusable message templates with parameters, useful
            for driving LLM interactions or Tool input.
          </p>
          <div class="flex items-center">
            <input
              type="checkbox"
              id="show-inactive-prompts"
              class="mr-2"
              onchange="toggleInactiveItems('prompts')"
            />
            <label
              for="show-inactive-prompts"
              class="text-sm font-medium text-gray-700 dark:text-gray-300"
              >Show Inactive</label
            >
          </div>
        </div>

        <!-- Tag Filtering for Prompts -->
        <div class="bg-white shadow rounded-lg p-4 mb-4 dark:bg-gray-800">
          <div class="flex items-center space-x-4">
            <label class="text-sm font-medium text-gray-700 dark:text-gray-300"
              >Filter by Tags:</label
            >
            <input
              type="text"
              id="prompts-tag-filter"
              placeholder="Enter tags (comma-separated)"
              class="flex-1 rounded-md border border-gray-300 dark:border-gray-600 shadow-sm px-3 py-1 text-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:text-gray-300"
              oninput="filterEntitiesByTags('prompts', this.value)"
            />
            <button
              onclick="clearTagFilter('prompts')"
              class="px-3 py-1 text-xs bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 rounded hover:bg-gray-300 dark:hover:bg-gray-500"
            >
              Clear
            </button>
          </div>
          <div class="mt-2">
            <span class="text-xs text-gray-500 dark:text-gray-400"
              >Available tags:</span
            >
            <div id="prompts-available-tags" class="mt-1 flex flex-wrap gap-1">
              <!-- Tag suggestions will be populated here by JavaScript -->
            </div>
          </div>
        </div>
        <div class="bg-white shadow rounded-lg p-6 mb-8 dark:bg-gray-800">
          <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
              <thead class="bg-gray-50 dark:bg-gray-700">
                <tr>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    ID
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Name
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Description
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Arguments
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Tags
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Status
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody
                class="bg-white divide-y divide-gray-200 dark:bg-gray-900 dark:divide-gray-700"
              >
                {% for prompt in prompts %}
                <tr>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100"
                  >
                    {{ prompt.id }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100"
                  >
                    {{ prompt.name }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300"
                  >
                    {{ prompt.description }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-300"
                  >
                    {% for arg in prompt.arguments %}{{ arg.name }}{% if not
                    loop.last %}, {% endif %}{% endfor %}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    {% if prompt.tags %} {% for tag in prompt.tags %}
                    <span
                      class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800 mr-1 mb-1"
                      >{{ tag }}</span
                    >
                    {% endfor %} {% else %}
                    <span class="text-gray-500 dark:text-gray-300 text-xs"
                      >None</span
                    >
                    {% endif %}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    <span
                      class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full {% if prompt.isActive %}bg-green-100 text-green-800{% else %}bg-red-100 text-red-800{% endif %}"
                    >
                      {{ "Active" if prompt.isActive else "Inactive" }}
                    </span>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    {% if prompt.isActive %}
                    <form
                      method="POST"
                      action="{{ root_path }}/admin/prompts/{{ prompt.id }}/toggle"
                      class="inline mr-2"
                      onsubmit="return handleToggleSubmit(event, 'prompts')"
                    >
                      <input type="hidden" name="activate" value="false" />
                      <button
                        type="submit"
                        x-tooltip="'💡Temporarily disable this item (can be re-activated).'"
                        class="text-yellow-600 hover:text-yellow-900"
                      >
                        Deactivate
                      </button>
                    </form>
                    {% else %}
                    <form
                      method="POST"
                      action="{{ root_path }}/admin/prompts/{{ prompt.id }}/toggle"
                      class="inline mr-2"
                      onsubmit="return handleToggleSubmit(event, 'prompts')"
                    >
                      <input type="hidden" name="activate" value="true" />
                      <button
                        type="submit"
                        x-tooltip="'💡Re-enable an inactive item.'"
                        class="text-blue-600 hover:text-blue-900"
                      >
                        Activate
                      </button>
                    </form>
                    {% endif %}
                    <button
                      onclick="viewPrompt('{{ prompt.name }}')"
                      class="text-indigo-600 dark:text-indigo-500 hover:text-indigo-900 mr-2"
                    >
                      View
                    </button>
                    <button
                      onclick="editPrompt('{{ prompt.name }}')"
                      class="text-green-600 hover:text-green-900 mr-2"
                    >
                      Edit
                    </button>
                    <form
                      method="POST"
                      action="{{ root_path }}/admin/prompts/{{ prompt.name }}/delete"
                      class="inline"
                      onsubmit="return handleSubmitWithConfirmation(event, 'prompts')"
                    >
                      <button
                        type="submit"
                        x-tooltip="'💡Permanently delete this item – cannot be undone.'"
                        class="text-red-600 hover:text-red-900"
                      >
                        Delete
                      </button>
                    </form>
                  </td>
                </tr>
                {% endfor %}
              </tbody>
            </table>
          </div>
        </div>

        <div class="bg-white shadow rounded-lg p-6 dark:bg-gray-800">
          <h3 class="text-lg font-bold mb-4 dark:text-gray-200">
            Add New Prompt
          </h3>
          <form
            method="POST"
            action="{{ root_path }}/admin/prompts"
            id="add-prompt-form"
          >
            <div class="grid grid-cols-1 gap-6">
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Name</label
                >
                <input
                  type="text"
                  name="name"
                  required
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Description</label
                >
                <textarea
                  name="description"
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                ></textarea>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Template</label
                >
                <textarea
                  name="template"
                  id="prompt-template-editor"
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 bg-gray-200 dark:bg-gray-800 dark:placeholder-gray-300 dark:text-gray-300"
                  placeholder=""
                ></textarea>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Arguments (JSON)</label
                >
                <textarea
                  name="arguments"
                  id="prompt-args-editor"
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  placeholder="[{'name':'arg1','description':'Argument 1','required':true}]"
                ></textarea>
              </div>
            </div>
            <div id="add-prompts-loading" style="display: none">
              <div class="spinner"></div>
            </div>
            <div id="status-prompts"></div>
            <div>
              <label
                class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                >Tags</label
              >
              <input
                type="text"
                name="tags"
                placeholder="e.g., greeting,template,conversation (comma-separated)"
                class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
              />
              <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                Enter tags separated by commas. Tags help categorize and filter
                prompts.
              </p>
            </div>
            <div class="mt-6">
              <button
                type="submit"
                x-tooltip="'💡Creates a reusable message template with parameters.'"
                class="inline-flex justify-center py-2 px-4 border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
              >
                Add Prompt
              </button>
            </div>
          </form>
        </div>
      </div>

      <!-- Gateways Panel -->
      <div id="gateways-panel" class="tab-panel hidden">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-2xl font-bold dark:text-gray-200">
            Federated Gateways (MCP Registry)
          </h2>
          <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
            Gateways are where you register external MCP servers to federate
            their tools/resources/prompts into your environment.
          </p>
          <div class="flex items-center">
            <input
              type="checkbox"
              id="show-inactive-gateways"
              class="mr-2"
              onchange="toggleInactiveItems('gateways')"
            />
            <label
              for="show-inactive-gateways"
              class="text-sm font-medium text-gray-700 dark:text-gray-300"
              >Show Inactive</label
            >
          </div>
        </div>

        <!-- Gateway Filter Section -->
        <div class="bg-white shadow rounded-lg p-4 mb-4 dark:bg-gray-800">
          <div class="flex flex-wrap gap-4 items-center">
            <div class="flex-1 min-w-64">
              <label
                for="gateway-tag-filter"
                class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                >Filter by Tags:</label
              >
              <input
                type="text"
                id="gateway-tag-filter"
                placeholder="e.g., production,external (comma-separated)"
                class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:text-gray-300"
                oninput="filterEntitiesByTags('gateways', this.value)"
              />
            </div>
            <div id="gateway-available-tags" class="flex flex-wrap gap-2">
              <!-- Available tags will be populated by JavaScript -->
            </div>
            <button
              onclick="clearTagFilter('gateways')"
              class="px-3 py-2 text-sm font-medium text-gray-700 bg-gray-100 border border-gray-300 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:bg-gray-600 dark:text-gray-300 dark:border-gray-500 dark:hover:bg-gray-500"
            >
              Clear Filter
            </button>
          </div>
        </div>

        <div class="bg-white shadow rounded-lg p-6 mb-8 dark:bg-gray-800">
          <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
              <thead class="bg-gray-50 dark:bg-gray-700">
                <tr>
                  <th
                    class="px-3 py-3 text-left text-xs font-medium text-gray-800 dark:text-gray-200 uppercase tracking-wider"
                  >
                    S. No.
                  </th>
                  <th
                    class="px-3 py-3 text-left text-xs font-medium text-gray-800 dark:text-gray-200 uppercase tracking-wider"
                  >
                    Name
                  </th>
                  <th
                    class="px-2 py-3 text-left text-xs font-medium text-gray-800 dark:text-gray-200 uppercase tracking-wider w-24"
                  >
                    URL
                  </th>
                  <th
                    class="px-3 py-3 text-left text-xs font-medium text-gray-800 dark:text-gray-200 uppercase tracking-wider"
                  >
                    Tags
                  </th>
                  <th
                    class="px-3 py-3 text-left text-xs font-medium text-gray-800 dark:text-gray-200 uppercase tracking-wider"
                  >
                    Status
                  </th>
                  <th
                    class="px-3 py-3 text-left text-xs font-medium text-gray-800 dark:text-gray-200 uppercase tracking-wider"
                  >
                    Last Seen
                  </th>
                  <th
                    class="px-3 py-3 text-left text-xs font-medium text-gray-800 dark:text-gray-200 uppercase tracking-wider"
                  >
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody
                class="bg-white divide-y divide-gray-200 dark:bg-gray-900 dark:divide-gray-700"
              >
                {% for gateway in gateways %}
                <tr>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100"
                  >
                    {{ loop.index }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100"
                  >
                    {{ gateway.name }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm text-gray-600 dark:text-gray-400"
                  >
                    {{ gateway.url }}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm">
                    {% if gateway.tags %} {% for tag in gateway.tags %}
                    <span
                      class="inline-block bg-blue-100 text-blue-800 text-xs px-2 py-1 rounded-full mr-1 mb-1"
                      >{{ tag }}</span
                    >
                    {% endfor %} {% else %}
                    <span class="text-gray-400">No tags</span>
                    {% endif %}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    {% set enabled = gateway.enabled %} {% set reachable =
                    gateway.reachable %} {% if enabled and reachable %} {% set
                    bg_class = "bg-green-100 text-green-800" %} {% elif enabled
                    and not reachable %} {% set bg_class = "bg-yellow-100
                    text-yellow-800" %} {% else %} {% set bg_class = "bg-red-100
                    text-red-800" %} {% endif %}

                    <!-- Wrapper for tooltip -->
                    <div class="relative group inline-block">
                      <span
                        class="px-2 inline-flex items-center text-xs leading-5 font-semibold rounded-full {{ bg_class }}"
                      >
                        {% if enabled %} {% if reachable %}
                        <!-- Active icon (green check) -->
                        Active
                        <svg
                          class="ml-1 h-4 w-4 text-green-600"
                          fill="currentColor"
                          viewBox="0 0 20 20"
                        >
                          <path
                            fill-rule="evenodd"
                            d="M10 18a8 8 0 100-16 8 8 0 000 16zm-1-4.586l5.293-5.293-1.414-1.414L9 11.586 7.121 9.707 5.707 11.121 9 14.414z"
                            clip-rule="evenodd"
                          />
                        </svg>
                        {% else %}
                        <!-- Offline icon (yellow warning) -->
                        Offline
                        <svg
                          class="ml-1 h-4 w-4 text-yellow-600"
                          fill="currentColor"
                          viewBox="0 0 20 20"
                        >
                          <path
                            fill-rule="evenodd"
                            d="M10 18a8 8 0 100-16 8 8 0 000 16zm-1-10h2v4h-2V8zm0 6h2v2h-2v-2z"
                            clip-rule="evenodd"
                          />
                        </svg>
                        {% endif %} {% else %}
                        <!-- Inactive icon (red error) -->
                        Inactive
                        <svg
                          class="ml-1 h-4 w-4 text-red-600"
                          fill="currentColor"
                          viewBox="0 0 20 20"
                        >
                          <path
                            fill-rule="evenodd"
                            d="M6.293 6.293a1 1 0 011.414 0L10 8.586l2.293-2.293a1 1 0 111.414 1.414L11.414 10l2.293 2.293a1 1 0 11-1.414 1.414L10 11.414l-2.293 2.293a1 1 0 11-1.414-1.414L8.586 10 6.293 7.707a1 1 0 010-1.414z"
                            clip-rule="evenodd"
                          />
                        </svg>
                        {% endif %}
                      </span>
                      <div
                        class="absolute left-full top-1/2 -translate-y-1/2 ml-2 hidden group-hover:block bg-gray-800 text-white text-xs rounded py-1 px-2 z-10 whitespace-nowrap shadow"
                      >
                        {% if not enabled %} 💡Gateway is Manually Deactivated
                        {% elif not reachable %} 💡Gateway is Not Reachable {%
                        else %} 💡Everything stable. {% endif %}
                      </div>
                    </div>
                  </td>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm text-gray-600 dark:text-gray-400"
                  >
                    {{ gateway.lastSeen.strftime('%Y-%m-%d %H:%M:%S') if
                    gateway.lastSeen else 'Never' }}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <button
                      onclick="testGateway('{{ gateway.url }}')"
                      class="text-stone-400 hover:text-stone-100 mr-2"
                    >
                      Test
                    </button>

                    <!-- Debug: Show gateway data for troubleshooting -->
                    <!-- Gateway ID: {{ gateway.id }} -->
                    <!-- Auth Type: {{ gateway.auth_type }} -->
                    <!-- OAuth Config: {{ gateway.oauth_config }} -->
                    <!-- Grant Type: {{ gateway.oauth_config.grant_type if gateway.oauth_config else 'None' }} -->
                    <script>
                      console.log("Auth Type:", "{{ gateway.authType }}");
                      console.log("OAuth Config:", "{{ gateway.oauthConfig }}");
                    </script>

                    {% if gateway.authType == 'oauth' %}
                    <a
                      href="{{ root_path }}/oauth/authorize/{{ gateway.id }}"
                      class="inline-block text-indigo-600 hover:text-indigo-500 mr-2"
                      title="🔐 Authorize Users for OAuth"
                    >
                      🔐 Authorize
                    </a>

                    <!-- Show Fetch Tools button if gateway is authorized but has no tools -->
                    <button
                      onclick="fetchToolsForGateway('{{ gateway.id }}', '{{ gateway.name }}')"
                      class="inline-block bg-green-600 hover:bg-green-700 text-white px-3 py-1 rounded text-sm mr-2"
                      title="🔧 Fetch Tools from MCP Server"
                      id="fetch-tools-{{ gateway.id }}"
                    >
                      🔧 Fetch Tools
                    </button>
                    {% endif %} {% if gateway.enabled %}
                    <form
                      method="POST"
                      action="{{ root_path }}/admin/gateways/{{ gateway.id }}/toggle"
                      class="inline mr-2"
                      onsubmit="return handleToggleSubmit(event, 'gateways')"
                    >
                      <input type="hidden" name="activate" value="false" />
                      <button
                        type="submit"
                        x-tooltip="'💡Temporarily disable this item (can be re-activated).'"
                        class="text-yellow-600 hover:text-yellow-200"
                      >
                        Deactivate
                      </button>
                    </form>
                    {% else %}
                    <form
                      method="POST"
                      action="{{ root_path }}/admin/gateways/{{ gateway.id }}/toggle"
                      class="inline mr-2"
                      onsubmit="return handleToggleSubmit(event, 'gateways')"
                    >
                      <input type="hidden" name="activate" value="true" />
                      <button
                        type="submit"
                        x-tooltip="'💡Re-enable an inactive item.'"
                        class="text-blue-600 hover:text-blue-200"
                      >
                        Activate
                      </button>
                    </form>
                    {% endif %}
                    <button
                      onclick="viewGateway('{{ gateway.id }}')"
                      class="text-indigo-600 dark:text-indigo-700 hover:text-indigo-100 mr-2"
                    >
                      View
                    </button>
                    <button
                      onclick="editGateway('{{ gateway.id }}')"
                      class="text-green-600 hover:text-green-300 mr-2"
                    >
                      Edit
                    </button>
                    <form
                      method="POST"
                      action="{{ root_path }}/admin/gateways/{{ gateway.id }}/delete"
                      class="inline"
                      onsubmit="return handleSubmitWithConfirmation(event, 'gateways')"
                    >
                      <button
                        type="submit"
                        x-tooltip="'💡Permanently delete this item – cannot be undone.'"
                        class="text-red-400 hover:text-red-600"
                      >
                        Delete
                      </button>
                    </form>
                  </td>
                </tr>
                {% endfor %}
              </tbody>
            </table>
          </div>
        </div>

        <div class="bg-white shadow rounded-lg p-6 dark:bg-gray-800">
          <h3 class="text-lg font-bold mb-4 dark:text-gray-200">
            Add New Gateway
          </h3>
          <form id="add-gateway-form">
            <div class="grid grid-cols-1 gap-6">
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Name</label
                >
                <input
                  type="text"
                  name="name"
                  required
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >URL</label
                >
                <input
                  type="url"
                  name="url"
                  required
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Description</label
                >
                <textarea
                  name="description"
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                ></textarea>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Tags</label
                >
                <input
                  type="text"
                  name="tags"
                  placeholder="e.g., production,external,api-gateway (comma-separated)"
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
                <p class="mt-1 text-sm text-gray-500">
                  Separate multiple tags with commas. Tags will be automatically
                  normalized (lowercase, spaces→hyphens).
                </p>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Transport Type</label
                >
                <select
                  name="transport"
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                >
                  <option value="SSE" selected>SSE</option>
                  <option value="STREAMABLEHTTP">Streamable HTTP</option>
                </select>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Authentication Type</label
                >
                <select
                  name="auth_type"
                  id="auth-type-gw"
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                >
                  <option value="">None</option>
                  <option value="basic">Basic</option>
                  <option value="bearer">Bearer Token</option>
                  <option value="authheaders">Custom Headers</option>
                  <option value="oauth">OAuth 2.0</option>
                </select>
              </div>
              <div id="auth-basic-fields-gw" style="display: none">
                <div>
                  <label class="block text-sm font-medium text-gray-700"
                    >Username</label
                  >
                  <input
                    type="text"
                    name="auth_username"
                    class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  />
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700"
                    >Password</label
                  >
                  <input
                    type="password"
                    name="auth_password"
                    class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  />
                </div>
              </div>
              <div id="auth-bearer-fields-gw" style="display: none">
                <div>
                  <label class="block text-sm font-medium text-gray-700"
                    >Token</label
                  >
                  <input
                    type="password"
                    name="auth_token"
                    class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  />
                </div>
              </div>
              <div id="auth-headers-fields-gw" style="display: none">
                <div class="space-y-3">
                  <div class="flex items-center justify-between">
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >
                      Custom Headers
                    </label>
                    <button
                      type="button"
                      onclick="addAuthHeader('auth-headers-container-gw')"
                      class="inline-flex items-center px-3 py-1 border border-transparent text-sm leading-4 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                    >
                      <svg
                        class="w-4 h-4 mr-1"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          stroke-linecap="round"
                          stroke-linejoin="round"
                          stroke-width="2"
                          d="M12 6v6m0 0v6m0-6h6m-6 0H6"
                        ></path>
                      </svg>
                      Add Header
                    </button>
                  </div>
                  <div id="auth-headers-container-gw" class="space-y-2">
                    <!-- Headers will be added dynamically here -->
                  </div>
                  <input
                    type="hidden"
                    name="auth_headers"
                    id="auth-headers-json-gw"
                  />
                </div>
              </div>

              <!-- OAuth Configuration Fields -->
              <div id="auth-oauth-fields-gw" style="display: none">
                <div class="space-y-4">
                  <div>
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >
                      Grant Type
                    </label>
                    <select
                      name="oauth_grant_type"
                      id="oauth-grant-type-gw"
                      class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                    >
                      <option value="client_credentials">
                        Client Credentials (Machine-to-Machine)
                      </option>
                      <option value="authorization_code">
                        Authorization Code (User Delegation)
                      </option>
                    </select>
                  </div>

                  <div>
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >
                      Client ID
                    </label>
                    <input
                      type="text"
                      name="oauth_client_id"
                      class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      placeholder="Your OAuth client ID"
                    />
                  </div>

                  <div>
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >
                      Client Secret
                    </label>
                    <input
                      type="password"
                      name="oauth_client_secret"
                      class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      placeholder="Your OAuth client secret"
                    />
                  </div>

                  <div>
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >
                      Token URL
                    </label>
                    <input
                      type="url"
                      name="oauth_token_url"
                      class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      placeholder="https://oauth.example.com/token"
                    />
                  </div>

                  <div id="oauth-auth-code-fields-gw" style="display: none">
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                      >
                        Authorization URL
                      </label>
                      <input
                        type="url"
                        name="oauth_authorization_url"
                        class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                        placeholder="https://oauth.example.com/authorize"
                      />
                      <p class="mt-1 text-sm text-gray-500">
                        The OAuth provider's authorization endpoint URL
                      </p>
                    </div>

                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                      >
                        Redirect URI
                      </label>
                      <input
                        type="url"
                        name="oauth_redirect_uri"
                        class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                        placeholder="https://gateway.example.com/oauth/callback"
                      />
                      <p class="mt-1 text-sm text-gray-500">
                        This must match the redirect URI configured in your
                        OAuth application
                      </p>
                      <p class="mt-1 text-sm text-blue-600 font-medium">
                        💡 Use:
                        <code class="bg-blue-100 px-1 rounded"
                          >{{ request.base_url }}oauth/callback</code
                        >
                      </p>
                    </div>

                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                      >
                        Token Management
                      </label>
                      <div class="mt-2 space-y-2">
                        <label class="flex items-center">
                          <input
                            type="checkbox"
                            name="oauth_store_tokens"
                            checked
                            class="rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"
                          />
                          <span
                            class="ml-2 text-sm text-gray-700 dark:text-gray-300"
                          >
                            Store access tokens for reuse
                          </span>
                        </label>
                        <label class="flex items-center">
                          <input
                            type="checkbox"
                            name="oauth_auto_refresh"
                            checked
                            class="rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"
                          />
                          <span
                            class="ml-2 text-sm text-gray-700 dark:text-gray-300"
                          >
                            Automatically refresh expired tokens
                          </span>
                        </label>
                      </div>
                      <p class="mt-1 text-sm text-gray-500">
                        Token management options for Authorization Code flow
                      </p>
                    </div>

                    <div
                      class="bg-blue-50 border border-blue-200 rounded-md p-4 dark:bg-blue-900/20 dark:border-blue-800"
                    >
                      <div class="flex">
                        <div class="flex-shrink-0">
                          <svg
                            class="h-5 w-5 text-blue-400"
                            viewBox="0 0 20 20"
                            fill="currentColor"
                          >
                            <path
                              fill-rule="evenodd"
                              d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z"
                              clip-rule="evenodd"
                            />
                          </svg>
                        </div>
                        <div class="ml-3">
                          <h3
                            class="text-sm font-medium text-blue-800 dark:text-blue-200"
                          >
                            Authorization Code Flow Setup
                          </h3>
                          <div
                            class="mt-2 text-sm text-blue-700 dark:text-blue-300"
                          >
                            <p>After creating this gateway, you'll need to:</p>
                            <ol class="list-decimal list-inside mt-1 space-y-1">
                              <li>
                                Click the "🔐 Authorize" button in the gateway
                                list
                              </li>
                              <li>
                                Complete the OAuth consent flow with your
                                provider
                              </li>
                              <li>
                                Return to the admin panel to see authorization
                                status
                              </li>
                            </ol>
                            <p class="mt-2 font-medium">
                              Note: The gateway will be created but tools won't
                              work until OAuth authorization is completed.
                            </p>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>

                  <div>
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                    >
                      Scopes
                    </label>
                    <input
                      type="text"
                      name="oauth_scopes"
                      class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      placeholder="repo read:user (space-separated)"
                    />
                    <p class="mt-1 text-sm text-gray-500">
                      Space-separated list of OAuth scopes (e.g., "repo
                      read:user")
                    </p>
                  </div>
                </div>
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                  >Passthrough Headers</label
                >
                <small class="text-gray-500 dark:text-gray-400 block mb-2">
                  List of headers to pass through from client requests
                  (comma-separated, e.g., "Authorization, X-Tenant-Id,
                  X-Trace-Id"). Leave empty to use global defaults.
                </small>
                <input
                  type="text"
                  name="passthrough_headers"
                  placeholder="Authorization, X-Tenant-Id, X-Trace-Id"
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                />
              </div>
              <div id="add-gateway-loading" style="display: none">
                <div class="spinner"></div>
              </div>
              <div id="status-gateways"></div>
            </div>
            <div class="mt-6">
              <button
                type="submit"
                x-tooltip="'💡Registers an external MCP server and imports its catalogs - Tools, Prompts, Resources, etc.'"
                class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
              >
                Add Gateway
              </button>
            </div>
          </form>
        </div>
      </div>

      <!-- A2A Agents Panel -->
      {% if a2a_enabled %}
      <div id="a2a-agents-panel" class="tab-panel hidden">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-2xl font-bold dark:text-gray-200">
            A2A Agents Catalog
          </h2>
          <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
            Manage Agent-to-Agent compatible agents that can be integrated as
            tools
          </p>
          <div class="flex items-center">
            <input
              type="checkbox"
              id="show-inactive-a2a-agents"
              class="mr-2"
              onchange="toggleInactiveItems('a2a-agents')"
            />
            <label
              for="show-inactive-a2a-agents"
              class="text-sm font-medium text-gray-700 dark:text-gray-300"
              >Show Inactive</label
            >
          </div>
        </div>

        <!-- A2A Agent Filter Section -->
        <div class="bg-white shadow rounded-lg p-4 mb-4 dark:bg-gray-800">
          <div class="flex flex-wrap gap-4 items-center">
            <div class="flex-1 min-w-64">
              <label
                for="a2a-agent-tag-filter"
                class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                >Filter by Tags:</label
              >
              <input
                type="text"
                id="a2a-agent-tag-filter"
                placeholder="e.g., ai,assistant (comma-separated)"
                class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:text-gray-300"
                oninput="filterEntitiesByTags('a2a-agents', this.value)"
              />
            </div>
            <div id="a2a-agent-available-tags" class="flex flex-wrap gap-2">
              <!-- Available tags will be populated by JavaScript -->
            </div>
            <button
              onclick="clearTagFilter('a2a-agents')"
              class="px-3 py-2 text-sm font-medium text-gray-700 bg-gray-100 border border-gray-300 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:bg-gray-600 dark:text-gray-300 dark:border-gray-500 dark:hover:bg-gray-500"
            >
              Clear Filter
            </button>
          </div>
        </div>

        <!-- A2A Agent Add Form -->
        <div class="bg-white shadow rounded-lg p-6 mb-6 dark:bg-gray-800">
          <h3 class="text-lg font-medium text-gray-900 dark:text-gray-200 mb-4">
            Add New A2A Agent
          </h3>
          <form
            method="post"
            action="{{ root_path }}/admin/a2a"
            class="grid grid-cols-1 gap-4 sm:grid-cols-2"
          >
            <div>
              <label
                for="a2a-agent-name"
                class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                >Agent Name</label
              >
              <input
                type="text"
                id="a2a-agent-name"
                name="name"
                required
                class="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:text-gray-300"
                placeholder="my-assistant-agent"
              />
            </div>
            <div>
              <label
                for="a2a-agent-endpoint-url"
                class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                >Endpoint URL</label
              >
              <input
                type="url"
                id="a2a-agent-endpoint-url"
                name="endpoint_url"
                required
                class="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:text-gray-300"
                placeholder="https://api.example.com/agent"
              />
            </div>
            <div>
              <label
                for="a2a-agent-type"
                class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                >Agent Type</label
              >
              <select
                id="a2a-agent-type"
                name="agent_type"
                class="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:text-gray-300"
              >
                <option value="generic">Generic</option>
                <option value="openai">OpenAI</option>
                <option value="anthropic">Anthropic</option>
                <option value="custom">Custom</option>
              </select>
            </div>
            <div>
              <label
                for="a2a-agent-auth-type"
                class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                >Authentication Type</label
              >
              <select
                id="a2a-agent-auth-type"
                name="auth_type"
                class="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:text-gray-300"
              >
                <option value="">None</option>
                <option value="api_key">API Key</option>
                <option value="bearer">Bearer Token</option>
                <option value="oauth">OAuth</option>
              </select>
            </div>
            <div class="sm:col-span-2">
              <label
                for="a2a-agent-description"
                class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                >Description</label
              >
              <textarea
                id="a2a-agent-description"
                name="description"
                rows="2"
                class="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:text-gray-300"
                placeholder="Description of the agent's capabilities"
              ></textarea>
            </div>
            <div>
              <label
                for="a2a-agent-auth-value"
                class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                >Authentication Value</label
              >
              <input
                type="password"
                id="a2a-agent-auth-value"
                name="auth_value"
                class="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:text-gray-300"
                placeholder="API key, token, etc."
              />
            </div>
            <div>
              <label
                for="a2a-agent-tags"
                class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                >Tags</label
              >
              <input
                type="text"
                id="a2a-agent-tags"
                name="tags"
                class="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:text-gray-300"
                placeholder="ai,assistant,production (comma-separated)"
              />
            </div>
            <div class="sm:col-span-2">
              <button
                type="submit"
                class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
              >
                Add A2A Agent
              </button>
            </div>
          </form>
        </div>

        <!-- A2A Agents List -->
        <div class="bg-white shadow rounded-lg dark:bg-gray-800">
          <div class="p-6">
            <h3
              class="text-lg font-medium text-gray-900 dark:text-gray-200 mb-4"
            >
              Registered A2A Agents
            </h3>
            <div class="space-y-4">
              {% if a2a_agents %} {% for agent in a2a_agents %}
              <div
                class="border border-gray-200 dark:border-gray-600 rounded-lg p-4 space-y-3"
              >
                <div class="flex items-start justify-between">
                  <div class="flex-1">
                    <h4
                      class="text-lg font-medium text-gray-900 dark:text-gray-200"
                    >
                      {{ agent.name }}
                    </h4>
                    <p class="text-sm text-gray-600 dark:text-gray-400">
                      {{ agent.description or "" }}
                    </p>
                    <div class="mt-2 flex flex-wrap gap-2">
                      <span
                        class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium {% if agent.enabled %}bg-green-100 text-green-800{% else %}bg-red-100 text-red-800{% endif %}"
                      >
                        {% if agent.enabled %}Active{% else %}Inactive{% endif
                        %}
                      </span>
                      <span
                        class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium {% if agent.reachable %}bg-green-100 text-green-800{% else %}bg-yellow-100 text-yellow-800{% endif %}"
                      >
                        {% if agent.reachable %}Reachable{% else %}Unreachable{%
                        endif %}
                      </span>
                      <span
                        class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800"
                      >
                        {{ agent.agentType }}
                      </span>
                      <span
                        class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800"
                      >
                        Auth: {{ agent.authType or "None" }}
                      </span>
                    </div>
                    <div class="mt-2 text-xs text-gray-500 dark:text-gray-400">
                      <div>Endpoint: {{ agent.endpointUrl }}</div>
                      <div>
                        Executions: {{ agent.metrics.totalExecutions }} |
                        Success Rate: {% if agent.metrics.totalExecutions %}{{
                        "%.1f"|format(100 - agent.metrics.failureRate) }}%{%
                        else %}N/A{% endif %}
                      </div>
                      <div>
                        Created: {{ agent.createdAt.strftime('%Y-%m-%d
                        %H:%M:%S') }}
                      </div>
                      {% if agent.lastInteraction %}
                      <div>
                        Last Interaction: {{
                        agent.lastInteraction.strftime('%Y-%m-%d %H:%M:%S') }}
                      </div>
                      {% endif %}
                    </div>
                    {% if agent.tags %}
                    <div class="mt-2 flex flex-wrap gap-1">
                      {% for tag in agent.tags %}
                      <span
                        class="inline-flex items-center px-2 py-1 rounded text-xs bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300"
                        >{{ tag }}</span
                      >
                      {% endfor %}
                    </div>
                    {% endif %}
                    <!-- Test result placeholder -->
                    <div
                      id="test-result-{{ agent.id }}"
                      class="mt-2 p-2 rounded-md bg-gray-50 dark:bg-gray-700 hidden"
                    ></div>
                  </div>
                  <div class="flex space-x-2">
                    <button
                      onclick="testA2AAgent('{{ agent.id }}', '{{ agent.name }}', '{{ agent.endpointUrl }}')"
                      class="px-3 py-1 text-sm font-medium text-blue-700 bg-blue-100 hover:bg-blue-200 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                    >
                      Test
                    </button>
                    <form
                      method="post"
                      action="{{ root_path }}/admin/a2a/{{ agent.id }}/toggle"
                      class="inline"
                    >
                      <input
                        type="hidden"
                        name="activate"
                        value="{% if agent.enabled %}false{% else %}true{% endif %}"
                      />
                      <button
                        type="submit"
                        class="px-3 py-1 text-sm font-medium {% if agent.enabled %}text-red-700 bg-red-100 hover:bg-red-200{% else %}text-green-700 bg-green-100 hover:bg-green-200{% endif %} rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                      >
                        {% if agent.enabled %}Deactivate{% else %}Activate{%
                        endif %}
                      </button>
                    </form>
                    <form
                      method="post"
                      action="{{ root_path }}/admin/a2a/{{ agent.id }}/delete"
                      class="inline"
                      onsubmit="return confirm('Are you sure you want to delete this A2A agent?')"
                    >
                      <button
                        type="submit"
                        class="px-3 py-1 text-sm font-medium text-red-700 bg-red-100 hover:bg-red-200 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500"
                      >
                        Delete
                      </button>
                    </form>
                  </div>
                </div>
              </div>
              {% endfor %} {% else %}
              <div class="text-center py-8">
                <p class="text-gray-500 dark:text-gray-400">
                  No A2A agents registered yet.
                </p>
              </div>
              {% endif %}
            </div>
          </div>
        </div>
      </div>
      {% endif %}

      <!-- Roots Panel -->
      <div id="roots-panel" class="tab-panel hidden">
        <!-- List of roots ------------------------------------------------------->
        <div class="bg-white shadow rounded-lg p-6 mb-8 dark:bg-gray-800">
          <!-- Consistent header -->
          <div class="flex justify-between items-center mb-4">
            <h2 class="text-2xl font-bold dark:text-gray-200">
              Root Directories
            </h2>
            <div class="flex items-center">
              <input
                type="checkbox"
                id="show-inactive-roots"
                class="mr-2"
                onchange="toggleInactiveItems('roots')"
              />
              <label
                for="show-inactive-roots"
                class="text-sm font-medium text-gray-700 dark:text-gray-300"
              >
                Show Inactive
              </label>
            </div>
          </div>

          <!-- Description -->
          <p class="text-sm text-gray-600 dark:text-gray-400 mb-4">
            Roots define the base folders accessible for file-based Resources.
            They enable MCP servers to browse local content.
          </p>

          <!-- Roots table -->
          <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
              <thead class="bg-gray-50 dark:bg-gray-700">
                <tr>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    ID
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    URI
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Name
                  </th>
                  <th
                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider"
                  >
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody
                class="bg-white divide-y divide-gray-200 dark:bg-gray-900 dark:divide-gray-700"
              >
                {% for root in roots %}
                <tr>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100"
                  >
                    {{ root.id }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100s"
                  >
                    {{ root.uri }}
                  </td>
                  <td
                    class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-500"
                  >
                    {{ root.name }}
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <form
                      method="POST"
                      action="{{ root_path }}/admin/roots/{{ root.uri }}/delete"
                      class="inline"
                      onsubmit="return handleSubmitWithConfirmation(event, 'roots')"
                    >
                      <button
                        type="submit"
                        x-tooltip="'💡Permanently delete this item – cannot be undone.'"
                        class="text-red-600 hover:text-red-900"
                      >
                        Delete
                      </button>
                    </form>
                  </td>
                </tr>
                {% endfor %}
              </tbody>
            </table>
          </div>
        </div>

        <!-- Add new root -------------------------------------------------------->
        <div class="bg-white shadow rounded-lg p-6 dark:bg-gray-800">
          <h3 class="text-lg font-bold mb-4 dark:text-gray-200">
            Add New Root
          </h3>
          <form
            method="POST"
            action="{{ root_path }}/admin/roots"
            id="add-root-form"
            onsubmit="return handleToggleSubmit(event, 'roots')"
          >
            <div class="grid grid-cols-1 gap-6">
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                  >URI</label
                >
                <input
                  type="text"
                  name="uri"
                  required
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  placeholder="file:///path/to/directory"
                />
              </div>
              <div>
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                  >Name</label
                >
                <input
                  type="text"
                  name="name"
                  class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-700 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                  placeholder="My Project"
                />
              </div>
            </div>
            <div class="mt-6">
              <button
                type="submit"
                x-tooltip="'💡Registers a base directory that MCP servers can browse for files.'"
                class="inline-flex justify-center py-2 px-4 border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
              >
                Add Root
              </button>
            </div>
          </form>
        </div>
      </div>

      <!-- Metrics Panel -->
      <div id="metrics-panel" class="tab-panel hidden">
        <div class="bg-white shadow rounded-lg p-6 dark:bg-gray-800">
          <h2 class="text-2xl font-bold dark:text-gray-200 mb-4">
            Aggregated Metrics
          </h2>
          <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
            Metrics provide visibility into Tool, Resource, Prompt, and Server
            usage across your Gateway-helpful for debugging and optimization.
          </p>

          <!-- Refresh button (also auto-refreshes when the tab is selected) -->
          <button
            onclick="loadAggregatedMetrics()"
            class="mb-4 px-4 py-2 bg-indigo-600 text-white rounded"
          >
            Refresh Metrics
          </button>

          <!-- Aggregated Metrics Table -->
          <div
            id="aggregated-metrics-content"
            class="overflow-auto mb-6 bg-gray-100"
          ></div>

          <!-- Overall Bar Chart for Total Executions -->
          <canvas
            id="metricsChart"
            width="400"
            height="200"
            class="bg-white"
          ></canvas>

          <hr class="my-6" />

          <!-- Expandable sections for top items -->
          <details id="top-tools-details" class="mb-4">
            <summary
              class="text-xl font-semibold cursor-pointer dark:text-gray-200"
            >
              Top Tools by Executions
            </summary>
            <div id="top-tools-content" class="mt-4"></div>
          </details>

          <details id="top-resources-details" class="mb-4">
            <summary
              class="text-xl font-semibold cursor-pointer dark:text-gray-200"
            >
              Top Resources by Executions
            </summary>
            <div id="top-resources-content" class="mt-4"></div>
          </details>

          <details id="top-servers-details" class="mb-4">
            <summary
              class="text-xl font-semibold cursor-pointer dark:text-gray-200"
            >
              Top Servers by Executions
            </summary>
            <div id="top-servers-content" class="mt-4"></div>
          </details>

          <details id="top-prompts-details" class="mb-4">
            <summary
              class="text-xl font-semibold cursor-pointer dark:text-gray-200"
            >
              Top Prompts by Executions
            </summary>
            <div id="top-prompts-content" class="mt-4"></div>
          </details>
        </div>
      </div>

      <!-- Modals -->
      <!-- Tool Detail Modal -->
      <div id="tool-modal" class="fixed z-10 inset-0 overflow-y-auto hidden">
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                Tool Details
              </h3>
              <div
                class="mt-4 space-y-4 bg-white dark:bg-gray-900"
                id="tool-details"
              ></div>
            </div>
            <div
              class="bg-gray-50 dark:bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse"
            >
              <button
                type="button"
                onclick="closeModal('tool-modal')"
                class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm dark:text-gray-300"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- Tool Test Modal -->
      <div
        id="tool-test-modal"
        class="fixed z-10 inset-0 overflow-y-auto hidden"
      >
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <!-- Increased max width (sm:max-w-2xl) for a larger modal -->
          <div
            class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-2xl sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <h3
                id="tool-test-modal-title"
                class="text-lg font-medium text-gray-900 dark:text-gray-100"
              >
                Test Tool
              </h3>
              <!-- New container to show the tool's description -->
              <div
                id="tool-test-modal-description"
                class="mb-4 text-gray-700 dark:text-gray-400"
              ></div>
              <form id="tool-test-form">
                <div
                  id="tool-test-form-fields"
                  class="space-y-4 text-gray-700 dark:text-gray-400"
                >
                  <!-- Fields will be dynamically inserted here based on the tool's input schema -->
                </div>
                <div class="mt-4 border-t pt-4">
                  <div>
                    <label
                      for="test-passthrough-headers"
                      class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                    >
                      Passthrough Headers (Optional)
                    </label>
                    <small class="text-gray-500 dark:text-gray-400 block mb-2">
                      Additional headers to send with the request (format:
                      "Header-Name: Value", one per line)
                    </small>
                    <textarea
                      id="test-passthrough-headers"
                      name="passthrough_headers"
                      rows="3"
                      placeholder="Authorization: Bearer your-token&#10;X-Tenant-Id: tenant-123&#10;X-Trace-Id: trace-456"
                      class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200"
                    ></textarea>
                  </div>
                </div>
                <div class="mt-4">
                  <button
                    type="button"
                    onclick="runToolTest()"
                    class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700"
                  >
                    Run Tool
                  </button>
                </div>
                <div id="tool-test-loading" style="display: none">
                  <div class="spinner"></div>
                </div>
              </form>
              <!-- The result area now uses a fixed height for a larger view -->
              <div
                id="tool-test-result"
                class="mt-4 bg-gray-100 p-2 rounded overflow-auto dark:bg-gray-900 dark:text-gray-300"
                style="height: 400px"
              ></div>
            </div>
            <div
              class="bg-gray-50 dark:bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse"
            >
              <button
                type="button"
                onclick="closeModal('tool-test-modal', 'tool-test-result')"
                class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm dark:text-gray-300"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- Tool Edit Modal -->
      <div
        id="tool-edit-modal"
        class="fixed z-10 inset-0 overflow-y-auto hidden"
      >
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                Edit Tool
              </h3>
              <div class="mt-4">
                <form id="edit-tool-form" method="POST">
                  <div class="grid grid-cols-1 gap-6">
                    <input type="hidden" name="name" id="edit-tool-name" />

                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Name</label
                      >
                      <input
                        type="text"
                        name="customName"
                        required
                        id="edit-tool-custom-name"
                        class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                    </div>

                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Display Name</label
                      >
                      <input
                        type="text"
                        name="displayName"
                        id="edit-tool-display-name"
                        placeholder="Custom display name for your UI"
                        class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                    </div>

                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >URL</label
                      >
                      <input
                        type="url"
                        name="url"
                        required
                        id="edit-tool-url"
                        class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                    </div>
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Description</label
                      >
                      <textarea
                        name="description"
                        id="edit-tool-description"
                        class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      ></textarea>
                    </div>
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Integration Type</label
                      >
                      <select
                        name="integrationType"
                        id="edit-tool-type"
                        class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                        onchange="handleEditIntegrationTypeChange()"
                      >
                        <option value="REST">REST</option>
                        <option value="MCP">MCP</option>
                      </select>
                    </div>
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Request Type</label
                      >
                      <select
                        name="requestType"
                        id="edit-tool-request-type"
                        class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      ></select>
                    </div>
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Headers (JSON)</label
                      >
                      <textarea
                        name="headers"
                        id="edit-tool-headers"
                        class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      ></textarea>
                    </div>
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Input Schema (JSON)</label
                      >
                      <textarea
                        name="input_schema"
                        id="edit-tool-schema"
                        class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      ></textarea>
                    </div>
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Annotations (JSON)</label
                      >
                      <textarea
                        name="annotations"
                        id="edit-tool-annotations"
                        class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm text-gray-900 placeholder-gray-600 dark:placeholder-gray-400 bg-white dark:bg-gray-800"
                        placeholder="Annotations are generally provided by the MCP servers"
                      ></textarea>
                      <p
                        class="mt-1 text-xs text-gray-500 dark:text-indigo-300"
                      >
                        Annotations like readOnlyHint, destructiveHint are
                        generally provided by the MCP server.
                      </p>
                    </div>
                    <!-- Authentication Section -->
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Authentication Type</label
                      >
                      <select
                        name="auth_type"
                        id="edit-auth-type"
                        class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      >
                        <option value="">None</option>
                        <option value="basic">Basic</option>
                        <option value="bearer">Bearer Token</option>
                        <option value="authheaders">Custom Headers</option>
                      </select>
                    </div>
                    <div id="edit-auth-basic-fields" style="display: none">
                      <div>
                        <label
                          class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >Username</label
                        >
                        <input
                          type="text"
                          name="auth_username"
                          id="edit-auth-username"
                          class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                        />
                      </div>
                      <div>
                        <label
                          class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >Password</label
                        >
                        <input
                          type="password"
                          name="auth_password"
                          id="edit-auth-password"
                          class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                          placeholder="********"
                        />
                      </div>
                    </div>
                    <div id="edit-auth-bearer-fields" style="display: none">
                      <div>
                        <label
                          class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >Token</label
                        >
                        <input
                          type="password"
                          name="auth_token"
                          id="edit-auth-token"
                          class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                          placeholder="********"
                        />
                      </div>
                    </div>
                  </div>
                  <div id="edit-auth-headers-fields" style="display: none">
                    <div class="space-y-3">
                      <div class="flex items-center justify-between">
                        <label
                          class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >
                          Custom Headers
                        </label>
                        <button
                          type="button"
                          onclick="addAuthHeader('edit-auth-headers-container')"
                          class="inline-flex items-center px-3 py-1 border border-transparent text-sm leading-4 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                        >
                          <svg
                            class="w-4 h-4 mr-1"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                          >
                            <path
                              stroke-linecap="round"
                              stroke-linejoin="round"
                              stroke-width="2"
                              d="M12 6v6m0 0v6m0-6h6m-6 0H6"
                            ></path>
                          </svg>
                          Add Header
                        </button>
                      </div>
                      <div id="edit-auth-headers-container" class="space-y-2">
                        <!-- Headers will be added dynamically here -->
                      </div>
                      <input
                        type="hidden"
                        name="auth_headers"
                        id="edit-auth-headers-json"
                      />
                    </div>
                  </div>
                  <!-- Tags Section -->
                  <div>
                    <label
                      class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                      >Tags</label
                    >
                    <input
                      type="text"
                      name="tags"
                      id="edit-tool-tags"
                      placeholder="e.g., api,data-processing,external (comma-separated)"
                      class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                    />
                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                      Enter tags separated by commas. Tags help categorize and
                      filter tools.
                    </p>
                  </div>
                  <div
                    class="mt-6 flex justify-end space-x-3 bg-white dark:bg-gray-900 dark:text-gray-100"
                  >
                    <button
                      type="button"
                      onclick="closeModal('tool-edit-modal')"
                      class="px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:text-gray-300"
                    >
                      Cancel
                    </button>
                    <button
                      type="submit"
                      class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                    >
                      Save Changes
                    </button>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Resource Detail Modal -->
      <div
        id="resource-modal"
        class="fixed z-10 inset-0 overflow-y-auto hidden"
      >
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                Resource Details
              </h3>
              <div
                class="mt-4 space-y-4 bg-white dark:bg-gray-400"
                id="resource-details"
              ></div>
            </div>
            <div
              class="bg-gray-50 dark:bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse"
            >
              <button
                type="button"
                onclick="closeModal('resource-modal')"
                class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm dark:text-gray-300"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- Resource Edit Modal -->
      <div
        id="resource-edit-modal"
        class="fixed z-10 inset-0 overflow-y-auto hidden"
      >
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                Edit Resource
              </h3>
              <div class="mt-4">
                <form id="edit-resource-form" method="POST">
                  <div class="grid grid-cols-1 gap-6">
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >URI</label
                      >
                      <!-- URI is read-only -->
                      <input
                        type="text"
                        name="uri"
                        required
                        id="edit-resource-uri"
                        readonly
                        class="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >Name</label
                      >
                      <input
                        type="text"
                        name="name"
                        required
                        id="edit-resource-name"
                        class="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >Description</label
                      >
                      <textarea
                        name="description"
                        id="edit-resource-description"
                        class="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      ></textarea>
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >MIME Type</label
                      >
                      <input
                        type="text"
                        name="mimeType"
                        id="edit-resource-mime-type"
                        class="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >Content</label
                      >
                      <!-- Remove required attribute to avoid browser validation issues -->
                      <textarea
                        name="content"
                        id="edit-resource-content"
                        class="mt-1 block w-full h-48 rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
                      ></textarea>
                    </div>
                    <!-- Tags Section -->
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Tags</label
                      >
                      <input
                        type="text"
                        name="tags"
                        id="edit-resource-tags"
                        placeholder="e.g., data,content,media (comma-separated)"
                        class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                      <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        Enter tags separated by commas. Tags help categorize and
                        filter resources.
                      </p>
                    </div>
                  </div>
                  <div
                    class="mt-6 flex justify-end space-x-3 bg-white dark:bg-gray-900 dark:text-gray-100"
                  >
                    <button
                      type="button"
                      onclick="closeModal('resource-edit-modal')"
                      class="px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:text-gray-300"
                    >
                      Cancel
                    </button>
                    <button
                      type="submit"
                      class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                    >
                      Save Changes
                    </button>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Prompt Detail Modal -->
      <div id="prompt-modal" class="fixed z-10 inset-0 overflow-y-auto hidden">
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                Prompt Details
              </h3>
              <div
                class="mt-4 space-y-4 bg-white dark:bg-gray-400"
                id="prompt-details"
              ></div>
            </div>
            <div
              class="bg-gray-50 dark:bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse"
            >
              <button
                type="button"
                onclick="closeModal('prompt-modal')"
                class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm dark:text-gray-300"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- Prompt Edit Modal -->
      <div
        id="prompt-edit-modal"
        class="fixed z-10 inset-0 overflow-y-auto hidden"
      >
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                Edit Prompt
              </h3>
              <div class="mt-4">
                <form id="edit-prompt-form" method="POST">
                  <div class="grid grid-cols-1 gap-6">
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >Name</label
                      >
                      <input
                        type="text"
                        name="name"
                        required
                        id="edit-prompt-name"
                        class="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >Description</label
                      >
                      <textarea
                        name="description"
                        id="edit-prompt-description"
                        class="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      ></textarea>
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >Template</label
                      >
                      <textarea
                        name="template"
                        id="edit-prompt-template"
                        class="mt-1 block w-full h-48 rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
                      ></textarea>
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >Arguments (JSON)</label
                      >
                      <textarea
                        name="arguments"
                        id="edit-prompt-arguments"
                        class="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      ></textarea>
                    </div>
                    <!-- Tags Section -->
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Tags</label
                      >
                      <input
                        type="text"
                        name="tags"
                        id="edit-prompt-tags"
                        placeholder="e.g., greeting,template,conversation (comma-separated)"
                        class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                      <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        Enter tags separated by commas. Tags help categorize and
                        filter prompts.
                      </p>
                    </div>
                  </div>
                  <div
                    class="mt-6 flex justify-end space-x-3 bg-white dark:bg-gray-900 dark:text-gray-100"
                  >
                    <button
                      type="button"
                      onclick="closeModal('prompt-edit-modal')"
                      class="px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:text-gray-300"
                    >
                      Cancel
                    </button>
                    <button
                      type="submit"
                      class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                    >
                      Save Changes
                    </button>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Gateway Detail Modal -->
      <div id="gateway-modal" class="fixed z-10 inset-0 overflow-y-auto hidden">
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                Gateway Details
              </h3>
              <div
                class="mt-4 space-y-4 bg-white dark:bg-gray-400"
                id="gateway-details"
              ></div>
            </div>
            <div
              class="bg-gray-50 dark:bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse"
            >
              <button
                type="button"
                onclick="closeModal('gateway-modal')"
                class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm dark:text-gray-300"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- Test Gateway Modal -->
      <div
        id="gateway-test-modal"
        class="fixed z-50 inset-0 bg-gray-800 bg-opacity-75 flex items-center justify-center hidden"
      >
        <div
          class="bg-white dark:bg-gray-900 w-full max-w-2xl max-h-[90vh] overflow-y-auto rounded-lg shadow-lg p-6"
        >
          <h2 class="text-xl font-bold mb-4 text-gray-800 dark:text-gray-100">
            Test Gateway Connectivity
          </h2>
          <form
            id="gateway-test-form"
            class="space-y-4 text-gray-800 dark:text-gray-100"
          >
            <div>
              <label
                for="gateway-test-url"
                class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                >Server URL</label
              >
              <input
                required
                name="url"
                type="text"
                id="gateway-test-url"
                class="mt-1 block w-full rounded-md shadow-sm p-1 bg-gray-200 dark:bg-gray-800"
              />
            </div>
            <div>
              <label
                for="gateway-test-method"
                class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                >Method</label
              >
              <select
                required
                name="method"
                id="gateway-test-method"
                class="mt-1 block w-full rounded-md shadow-sm p-1 bg-gray-200 dark:bg-gray-800"
              >
                <option>GET</option>
                <option>POST</option>
                <option>PUT</option>
                <option>DELETE</option>
                <option>PATCH</option>
              </select>
            </div>
            <div>
              <label
                for="gateway-test-path"
                class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                >Path</label
              >
              <input
                id="gateway-test-path"
                name="path"
                type="text"
                placeholder="/health"
                class="mt-1 block w-full rounded-md shadow-sm p-1 bg-gray-200 dark:bg-gray-800"
              />
            </div>
            <div>
              <label
                for="gateway-test-headers"
                class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                >Headers (JSON)</label
              >
              <textarea
                id="gateway-test-headers"
                class="mt-1 block w-full rounded-md shadow-sm p-1 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-300 placeholder-gray-600 dark:placeholder-gray-400"
                placeholder="Enter request headers as JSON"
              ></textarea>
            </div>

            <div>
              <label
                for="gateway-test-body"
                class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                >Body (JSON)</label
              >
              <textarea
                id="gateway-test-body"
                class="mt-1 block w-full rounded-md shadow-sm p-1 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-300 placeholder-gray-600 dark:placeholder-gray-400"
                placeholder="Enter request body as JSON"
              ></textarea>
            </div>

            <div class="flex">
              <button
                type="submit"
                id="gateway-test-submit"
                class="w-full text-center px-3 py-1 bg-indigo-600 text-white rounded hover:bg-indigo-700"
              >
                Test
              </button>
              <p class="p-1"></p>
              <button
                id="gateway-test-close"
                type="button"
                class="w-full text-center px-3 py-1 border border-blue-600 rounded bg-white text-gray-700 hover:bg-gray-200"
              >
                Close
              </button>
            </div>

            <div
              id="gateway-test-loading"
              class="mt-4 hidden flex items-center justify-center"
            >
              <div
                class="spinner border-t-4 border-blue-600 w-6 h-6 rounded-full animate-spin"
              ></div>
            </div>

            <div id="gateway-test-result" class="hidden">
              <label class="block text-sm font-medium text-gray-700"
                >Response</label
              >
              <div
                id="gateway-test-response-json"
                class="bg-gray-100 p-2 rounded overflow-auto text-sm text-gray-800 max-h-64"
              ></div>
            </div>
          </form>
        </div>
      </div>

      <!-- Gateway Edit Modal -->
      <div
        id="gateway-edit-modal"
        class="fixed z-10 inset-0 overflow-y-auto hidden"
      >
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                Edit Gateway
              </h3>
              <div class="mt-4">
                <form id="edit-gateway-form" method="POST">
                  <div class="grid grid-cols-1 gap-6">
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >Name</label
                      >
                      <input
                        type="text"
                        name="name"
                        required
                        id="edit-gateway-name"
                        class="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >URL</label
                      >
                      <input
                        type="url"
                        name="url"
                        required
                        id="edit-gateway-url"
                        class="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >Description</label
                      >
                      <textarea
                        name="description"
                        id="edit-gateway-description"
                        class="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      ></textarea>
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >Tags</label
                      >
                      <input
                        type="text"
                        name="tags"
                        id="edit-gateway-tags"
                        placeholder="e.g., production,external,api-gateway (comma-separated)"
                        class="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                      <p class="mt-1 text-sm text-gray-500">
                        Separate multiple tags with commas. Tags will be
                        automatically normalized.
                      </p>
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >Transport Type</label
                      >
                      <select
                        name="transport"
                        id="edit-gateway-transport"
                        class="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      >
                        <option value="SSE" selected>SSE</option>
                        <option value="STREAMABLEHTTP">Streamable HTTP</option>
                      </select>
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700"
                        >Authentication Type</label
                      >
                      <select
                        name="auth_type"
                        id="auth-type-gw-edit"
                        class="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      >
                        <option value="">None</option>
                        <option value="basic">Basic</option>
                        <option value="bearer">Bearer Token</option>
                        <option value="authheaders">Custom Headers</option>
                        <option value="oauth">OAuth 2.0</option>
                      </select>
                    </div>
                    <div id="auth-basic-fields-gw-edit" style="display: none">
                      <div>
                        <label class="block text-sm font-medium text-gray-700"
                          >Username</label
                        >
                        <input
                          type="text"
                          name="auth_username"
                          class="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                        />
                      </div>
                      <div>
                        <label class="block text-sm font-medium text-gray-700"
                          >Password</label
                        >
                        <input
                          type="password"
                          name="auth_password"
                          class="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                        />
                      </div>
                    </div>
                    <div id="auth-bearer-fields-gw-edit" style="display: none">
                      <div>
                        <label class="block text-sm font-medium text-gray-700"
                          >Token</label
                        >
                        <input
                          type="password"
                          name="auth_token"
                          class="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                        />
                      </div>
                    </div>
                    <div id="auth-headers-fields-gw-edit" style="display: none">
                      <div class="space-y-3">
                        <div class="flex items-center justify-between">
                          <label
                            class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >
                            Custom Headers
                          </label>
                          <button
                            type="button"
                            onclick="addAuthHeader('auth-headers-container-gw-edit')"
                            class="inline-flex items-center px-3 py-1 border border-transparent text-sm leading-4 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                          >
                            <svg
                              class="w-4 h-4 mr-1"
                              fill="none"
                              stroke="currentColor"
                              viewBox="0 0 24 24"
                            >
                              <path
                                stroke-linecap="round"
                                stroke-linejoin="round"
                                stroke-width="2"
                                d="M12 6v6m0 0v6m0-6h6m-6 0H6"
                              ></path>
                            </svg>
                            Add Header
                          </button>
                        </div>
                        <div
                          id="auth-headers-container-gw-edit"
                          class="space-y-2"
                        >
                          <!-- Headers will be added dynamically here -->
                        </div>
                        <input
                          type="hidden"
                          name="auth_headers"
                          id="auth-headers-json-gw-edit"
                        />
                      </div>
                    </div>

                    <!-- OAuth Configuration Fields -->
                    <div id="auth-oauth-fields-gw-edit" style="display: none">
                      <div class="space-y-4">
                        <div>
                          <label
                            class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >
                            Grant Type
                          </label>
                          <select
                            name="oauth_grant_type"
                            id="oauth-grant-type-gw-edit"
                            class="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                          >
                            <option value="client_credentials">
                              Client Credentials (Machine-to-Machine)
                            </option>
                            <option value="authorization_code">
                              Authorization Code (User Delegation)
                            </option>
                          </select>
                        </div>

                        <div>
                          <label
                            class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >
                            Client ID
                          </label>
                          <input
                            type="text"
                            name="oauth_client_id"
                            id="oauth-client-id-gw-edit"
                            class="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                            placeholder="Your OAuth client ID"
                          />
                        </div>

                        <div>
                          <label
                            class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >
                            Client Secret
                          </label>
                          <input
                            type="password"
                            name="oauth_client_secret"
                            id="oauth-client-secret-gw-edit"
                            class="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                            placeholder="Your OAuth client secret"
                          />
                          <p class="mt-1 text-sm text-gray-500">
                            Leave blank to retain the current secret.
                          </p>
                        </div>

                        <div>
                          <label
                            class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                          >
                            Token URL
                          </label>
                          <input
                            type="url"
                            name="oauth_token_url"
                            id="oauth-token-url-gw-edit"
                            class="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                            placeholder="https://oauth.example.com/token"
                          />
                        </div>

                        <div
                          id="oauth-auth-code-fields-gw-edit"
                          style="display: none"
                        >
                          <div>
                            <label
                              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                            >
                              Authorization URL
                            </label>
                            <input
                              type="url"
                              name="oauth_authorization_url"
                              id="oauth-authorization-url-gw-edit"
                              class="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                              placeholder="https://oauth.example.com/authorize"
                            />
                            <p class="mt-1 text-sm text-gray-500">
                              The OAuth provider's authorization endpoint URL
                            </p>
                          </div>

                          <div>
                            <label
                              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                            >
                              Redirect URI
                            </label>
                            <input
                              type="url"
                              name="oauth_redirect_uri"
                              id="oauth-redirect-uri-gw-edit"
                              class="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                              placeholder="https://gateway.example.com/oauth/callback"
                            />
                            <p class="mt-1 text-sm text-gray-500">
                              This must match the redirect URI configured in
                              your OAuth application
                            </p>
                            <p class="mt-1 text-sm text-blue-600 font-medium">
                              💡 Use:
                              <code class="bg-blue-100 px-1 rounded"
                                >http://localhost:4444/oauth/callback</code
                              >
                            </p>
                          </div>

                          <div>
                            <label
                              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                            >
                              Scopes
                            </label>
                            <input
                              type="text"
                              name="oauth_scopes"
                              id="oauth-scopes-gw-edit"
                              class="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                              placeholder="repo read:user (space-separated)"
                            />
                            <p class="mt-1 text-sm text-gray-500">
                              Space-separated list of OAuth scopes (e.g., "repo
                              read:user")
                            </p>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-400"
                        >Passthrough Headers</label
                      >
                      <small
                        class="text-gray-500 dark:text-gray-400 block mb-2"
                      >
                        List of headers to pass through from client requests
                        (comma-separated, e.g., "Authorization, X-Tenant-Id,
                        X-Trace-Id"). Leave empty to use global defaults.
                      </small>
                      <input
                        type="text"
                        name="passthrough_headers"
                        id="edit-gateway-passthrough-headers"
                        placeholder="Authorization, X-Tenant-Id, X-Trace-Id"
                        class="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                    </div>
                  </div>
                  <div
                    class="mt-6 flex justify-end space-x-3 bg-white dark:bg-gray-900 dark:text-gray-100"
                  >
                    <button
                      type="button"
                      onclick="closeModal('gateway-edit-modal')"
                      class="px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:text-gray-300"
                    >
                      Cancel
                    </button>
                    <button
                      type="submit"
                      class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                    >
                      Save Changes
                    </button>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Server Detail Modal -->
      <div id="server-modal" class="fixed z-10 inset-0 overflow-y-auto hidden">
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                Server Details
              </h3>
              <div
                class="mt-4 space-y-4 bg-white dark:bg-gray-900"
                id="server-details"
              ></div>
            </div>
            <div
              class="bg-gray-50 dark:bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse"
            >
              <button
                type="button"
                onclick="closeModal('server-modal')"
                class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm dark:text-gray-300"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- Server Edit Modal -->
      <div
        id="server-edit-modal"
        class="fixed z-10 inset-0 overflow-y-auto hidden"
      >
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                Edit Server
              </h3>
              <div class="mt-4">
                <form id="edit-server-form" method="POST">
                  <div class="grid grid-cols-1 gap-6">
                    <!-- Existing fields -->
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >UUID</label
                      >
                      <input
                        type="text"
                        name="id"
                        id="edit-server-id"
                        class="mt-1 block w-full rounded-md border border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                      <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
                        Changing UUID will create a new server endpoint. Use with caution.
                      </p>
                    </div>
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Name</label
                      >
                      <input
                        type="text"
                        name="name"
                        required
                        id="edit-server-name"
                        class="mt-1 block w-full rounded-md border border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                    </div>
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Description</label
                      >
                      <textarea
                        name="description"
                        id="edit-server-description"
                        class="mt-1 block w-full rounded-md border border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      ></textarea>
                    </div>
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Icon URL</label
                      >
                      <input
                        type="url"
                        name="icon"
                        id="edit-server-icon"
                        class="mt-1 block w-full rounded-md border border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                    </div>

                    <!-- Tags Section -->
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Tags</label
                      >
                      <input
                        type="text"
                        name="tags"
                        id="edit-server-tags"
                        placeholder="e.g., api,data-processing,external (comma-separated)"
                        class="mt-1 block w-full rounded-md border border-gray-300 dark:border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                      />
                      <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        Enter tags separated by commas. Tags help categorize and
                        filter servers.
                      </p>
                    </div>

                    <div
                      class="p-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-600"
                    >
                      <label
                        for="edit-server-tools"
                        class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2"
                      >
                        Associated Tools
                      </label>
                      <div
                        id="edit-server-tools"
                        class="max-h-60 overflow-y-auto rounded-md border border-gray-600 shadow-sm p-3 bg-gray-50 dark:bg-gray-900"
                      >
                        {% for tool in tools %}
                        <label
                          class="flex items-center space-x-3 text-gray-700 dark:text-gray-300 mb-2 cursor-pointer hover:bg-indigo-50 dark:hover:bg-indigo-900 rounded-md p-1"
                        >
                          <input
                            type="checkbox"
                            name="associatedTools"
                            value="{{ tool.id }}"
                            class="tool-checkbox form-checkbox h-5 w-5 text-indigo-600 dark:bg-gray-800 dark:border-gray-600"
                          />
                          <span class="select-none">{{ tool.displayName or tool.customName or tool.name }}</span>
                        </label>
                        {% endfor %}
                      </div>
                      <div class="flex justify-end gap-3 mt-3">
                        <button
                          type="button"
                          id="selectAllEditToolsBtn"
                          class="px-3 py-1 text-sm font-semibold text-green-600 border border-green-600 rounded-md hover:bg-green-50 focus:outline-none focus:ring-2 focus:ring-green-300 focus:ring-offset-1"
                          aria-label="Select all tools"
                        >
                          Select All
                        </button>

                        <button
                          type="button"
                          id="clearAllEditToolsBtn"
                          class="px-3 py-1 text-sm font-semibold text-red-600 border border-red-600 rounded-md hover:bg-red-50 focus:outline-none focus:ring-2 focus:ring-red-300 focus:ring-offset-1"
                          aria-label="Clear all selected tools"
                        >
                          Clear All
                        </button>
                      </div>

                      <!-- Selected pills -->
                      <div
                        id="selectedEditToolsPills"
                        class="mt-4 flex flex-wrap gap-2"
                      ></div>

                      <!-- Warning message -->
                      <div
                        id="selectedEditToolsWarning"
                        class="mt-2 min-h-[1.25rem] text-sm font-semibold text-yellow-600"
                        aria-live="polite"
                      ></div>
                    </div>

                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Associated Resources (comma-separated IDs)</label
                      >
                      <input
                        type="text"
                        name="associatedResources"
                        id="edit-server-resources"
                        class="mt-1 block w-full rounded-md border border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                        placeholder="e.g., 3,4"
                      />
                    </div>
                    <div>
                      <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300"
                        >Associated Prompts (comma-separated IDs)</label
                      >
                      <input
                        type="text"
                        name="associatedPrompts"
                        id="edit-server-prompts"
                        class="mt-1 block w-full rounded-md border border-gray-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 dark:bg-gray-900 dark:placeholder-gray-300 dark:text-gray-300"
                        placeholder="e.g., 5,6"
                      />
                    </div>
                  </div>
                  <div
                    class="mt-6 flex justify-end space-x-3 bg-white dark:bg-gray-900 dark:text-gray-100"
                  >
                    <button
                      type="button"
                      onclick="closeModal('server-edit-modal')"
                      class="px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:text-gray-300"
                    >
                      Cancel
                    </button>
                    <button
                      type="submit"
                      class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                    >
                      Save Changes
                    </button>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Config Selection Modal -->
      <div
        id="config-selection-modal"
        class="fixed z-10 inset-0 overflow-y-auto hidden"
      >
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <h3
                class="text-lg font-medium text-gray-900 dark:text-gray-100 mb-4"
              >
                Export Configuration for <span id="server-name-display"></span>
              </h3>
              <p class="text-sm text-gray-600 dark:text-gray-400 mb-6">
                Choose the configuration format for your MCP client:
              </p>

              <div class="space-y-3">
                <button
                  id="stdio-config-btn"
                  onclick="generateAndShowConfig('stdio')"
                  class="w-full flex items-center p-4 text-left border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-500"
                >
                  <span class="text-2xl mr-3">▶️</span>
                  <div>
                    <div class="font-medium text-gray-900 dark:text-gray-100">
                      Stdio (Claude Desktop, CLI)
                    </div>
                    <div class="text-sm text-gray-500 dark:text-gray-400">
                      For Claude Desktop, CLI tools, and stdio-based MCP clients
                    </div>
                  </div>
                </button>

                <button
                  id="sse-config-btn"
                  onclick="generateAndShowConfig('sse')"
                  class="w-full flex items-center p-4 text-left border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-500"
                >
                  <span class="text-2xl mr-3">🌐</span>
                  <div>
                    <div class="font-medium text-gray-900 dark:text-gray-100">
                      SSE (LangChain, LlamaIndex)
                    </div>
                    <div class="text-sm text-gray-500 dark:text-gray-400">
                      For frameworks supporting Server-Sent Events transport
                    </div>
                  </div>
                </button>

                <button
                  id="http-config-btn"
                  onclick="generateAndShowConfig('http')"
                  class="w-full flex items-center p-4 text-left border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-500"
                >
                  <span class="text-2xl mr-3">🔗</span>
                  <div>
                    <div class="font-medium text-gray-900 dark:text-gray-100">
                      HTTP (REST clients)
                    </div>
                    <div class="text-sm text-gray-500 dark:text-gray-400">
                      For REST clients and HTTP-based MCP integrations
                    </div>
                  </div>
                </button>
              </div>
            </div>
            <div
              class="bg-gray-50 dark:bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse"
            >
              <button
                type="button"
                onclick="closeModal('config-selection-modal')"
                class="w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:w-auto sm:text-sm dark:text-gray-300"
              >
                Cancel
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- Config Display Modal -->
      <div
        id="config-display-modal"
        class="fixed z-10 inset-0 overflow-y-auto hidden"
      >
        <div
          class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0"
        >
          <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
          </div>
          <div
            class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-3xl sm:w-full"
          >
            <div
              class="bg-white dark:bg-gray-900 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"
            >
              <div class="flex items-center justify-between mb-4">
                <h3
                  class="text-lg font-medium text-gray-900 dark:text-gray-100"
                >
                  <span id="config-display-title">Client Configuration</span>
                </h3>
                <button
                  onclick="copyConfigToClipboard()"
                  class="inline-flex items-center px-3 py-1 border border-transparent text-sm leading-4 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                >
                  📋 Copy to Clipboard
                </button>
              </div>

              <div class="mb-4">
                <p class="text-sm text-gray-600 dark:text-gray-400 mb-2">
                  <span id="config-description"></span>
                </p>
                <div
                  class="bg-gray-100 dark:bg-gray-800 rounded p-2 text-xs text-gray-600 dark:text-gray-400"
                >
                  <strong>Usage:</strong> <span id="config-usage"></span>
                </div>
              </div>

              <div class="relative">
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
                >
                  Configuration JSON:
                </label>
                <div class="relative">
                  <textarea
                    id="config-content"
                    readonly
                    class="w-full h-80 p-3 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-800 dark:text-gray-200 font-mono text-sm"
                    style="tab-size: 2"
                  ></textarea>
                </div>
              </div>
            </div>
            <div
              class="bg-gray-50 dark:bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse"
            >
              <button
                onclick="downloadConfig()"
                class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-green-600 text-base font-medium text-white hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 sm:ml-3 sm:w-auto sm:text-sm"
              >
                💾 Download JSON
              </button>
              <button
                onclick="goBackToSelection()"
                class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm dark:text-gray-300"
              >
                ← Back
              </button>
              <button
                type="button"
                onclick="closeModal('config-display-modal')"
                class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm dark:text-gray-300"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- Scripts -->
    <script>
      // Build mapping objects using your existing tools, resources, and prompts arrays
      window.toolMapping = {};
      {% for tool in tools %}
      window.toolMapping["{{ tool.id }}"] = "{{ tool.name }}";
      {% endfor %}

      window.resourceMapping = {};
      {% for resource in resources %}
      window.resourceMapping["{{ resource.id }}"] = "{{ resource.name }}";
      {% endfor %}

      window.promptMapping = {};
      {% for prompt in prompts %}
      window.promptMapping["{{ prompt.id }}"] = "{{ prompt.name }}";
      {% endfor %}

      window.ROOT_PATH = {{ root_path | tojson }};
      window.GATEWAY_TOOL_NAME_SEPARATOR = {{ gateway_tool_name_separator | tojson }};
      window.MAX_NAME_LENGTH = {{ max_name_length | tojson }};

      // Tag filtering functionality moved to admin.js
      function clearTagFilter(entityType) {
        const input = document.getElementById(entityType + '-tag-filter');
        input.value = '';
        // Use the corrected filterEntitiesByTags function from admin.js
        if (typeof filterEntitiesByTags === 'function') {
          filterEntitiesByTags(entityType, '');
        }
      }

      // updateAvailableTags function moved to admin.js with proper tag element selectors

      // addTagToFilter function moved to admin.js

      // Initialize tag suggestions when page loads - using functions from admin.js
      document.addEventListener('DOMContentLoaded', function() {
        ['tools', 'resources', 'prompts', 'servers', 'gateways'].forEach(entityType => {
          // Use the corrected functions from admin.js
          if (typeof updateAvailableTags === 'function') {
            updateAvailableTags(entityType);
          }
        });
      });

      // Add search functionality for filtering tools
      document.addEventListener('DOMContentLoaded', function() {
        const searchBox = document.getElementById('searchTools');
        const toolItems = document.querySelectorAll('#associatedTools .tool-item');
        const noToolsMessage = document.getElementById('noToolsMessage');
        const searchQuerySpan = document.getElementById('searchQuery');

        searchBox.addEventListener('input', function() {
          const filter = this.value.toLowerCase();
          let hasVisibleItems = false;

          toolItems.forEach(function(toolItem) {
            const toolName = toolItem.querySelector('span').textContent.toLowerCase();
            if (toolName.includes(filter)) {
              toolItem.style.display = '';
              hasVisibleItems = true;
            } else {
              toolItem.style.display = 'none';
            }
          });

          if (hasVisibleItems) {
            noToolsMessage.style.display = 'none';
          } else {
            searchQuerySpan.textContent = filter;
            noToolsMessage.style.display = 'block';
          }
        });
      });
    </script>
    <script>
      function handleEditIntegrationTypeChange() {
        const typeSel = document.getElementById("edit-tool-type");
        const reqSel = document.getElementById("edit-tool-request-type");
        if (!typeSel || !reqSel) return;

        const isREST = typeSel.value === "REST";
        // For REST tools, enable HTTP verbs; for MCP, disable & clear to avoid bad values.
        reqSel.disabled = !isREST;
        if (!isREST) {
          reqSel.value = "";
        }
      }

      // When the Edit modal is shown, re-evaluate enable/disable based on prefilled value.
      (function () {
        const modal = document.getElementById("tool-edit-modal");
        if (!modal) return;

        const observer = new MutationObserver(() => {
          const isOpen = !modal.classList.contains("hidden");
          if (isOpen) {
            // Defer one tick so existing JS can prefill values first.
            setTimeout(handleEditIntegrationTypeChange, 0);
          }
        });
        observer.observe(modal, {
          attributes: true,
          attributeFilter: ["class"],
        });
      })();

      // Logs functionality
      let logStreamSource = null;
      let currentLogPage = 0;
      const logsPerPage = 100;

      async function refreshLogs() {
        const level = document.getElementById("log-level-filter").value;
        const entityType = document.getElementById("log-entity-filter").value;
        const search = document.getElementById("log-search").value;

        const params = new URLSearchParams({
          limit: logsPerPage,
          offset: currentLogPage * logsPerPage,
          order: "desc",
        });

        if (level) params.append("level", level);
        if (entityType) params.append("entity_type", entityType);
        if (search) params.append("search", search);

        try {
          const headers = {};
          const token = localStorage.getItem("token");
          if (token) {
            headers["Authorization"] = `Bearer ${token}`;
          }

          const response = await fetch(
            `${window.ROOT_PATH || ""}/admin/logs?${params}`,
            {
              headers: headers,
              credentials: "same-origin",
            },
          );

          if (!response.ok) throw new Error(`HTTP ${response.status}`);

          const data = await response.json();
          displayLogs(data.logs);
          updateLogStats(data.stats);
          updateLogCount(data.total);
        } catch (error) {
          console.error("Error fetching logs:", error);
          showErrorMessage("Failed to fetch logs");
        }
      }

      function displayLogs(logs) {
        const tbody = document.getElementById("logs-tbody");
        tbody.innerHTML = "";

        logs.forEach((log) => {
          const row = document.createElement("tr");
          row.className = "hover:bg-gray-50 dark:hover:bg-gray-700";

          const timestamp = new Date(log.timestamp).toLocaleString();
          const levelClass = getLevelClass(log.level);
          const entity = log.entity_name || log.entity_id || "-";

          row.innerHTML = `
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
              ${timestamp}
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
              <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${levelClass}">
                ${log.level}
              </span>
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
              ${log.entity_type ? `${log.entity_type}: ${entity}` : entity}
            </td>
            <td class="px-6 py-4 text-sm text-gray-900 dark:text-gray-100">
              ${escapeHtml(log.message)}
            </td>
          `;

          tbody.appendChild(row);
        });
      }

      function getLevelClass(level) {
        switch (level) {
          case "debug":
            return "bg-gray-100 text-gray-800";
          case "info":
            return "bg-blue-100 text-blue-800";
          case "warning":
            return "bg-yellow-100 text-yellow-800";
          case "error":
            return "bg-red-100 text-red-800";
          case "critical":
            return "bg-red-600 text-white";
          default:
            return "bg-gray-100 text-gray-800";
        }
      }

      function updateLogStats(stats) {
        if (!stats) return;

        const statsDiv = document.getElementById("log-stats");
        const levelDist = stats.level_distribution || {};
        const entityDist = stats.entity_distribution || {};

        let html = `
          <div class="flex flex-wrap gap-4 text-sm">
            <span>Buffer: ${stats.usage_percent || 0}% (${stats.buffer_size_mb || 0}/${stats.max_size_mb || 0} MB)</span>
            <span>Total: ${stats.total_logs || 0} logs</span>
        `;

        if (Object.keys(levelDist).length > 0) {
          html += "<span>Levels: ";
          for (const [level, count] of Object.entries(levelDist)) {
            html += `${level}(${count}) `;
          }
          html += "</span>";
        }

        html += "</div>";
        statsDiv.innerHTML = html;
      }

      function updateLogCount(total) {
        document.getElementById("log-count").textContent = `${total} logs`;

        // Update pagination buttons
        document.getElementById("prev-page").disabled = currentLogPage === 0;
        document.getElementById("next-page").disabled =
          (currentLogPage + 1) * logsPerPage >= total;
      }

      function toggleLogStream() {
        const button = document.getElementById("stream-toggle");

        if (logStreamSource) {
          // Stop streaming
          logStreamSource.close();
          logStreamSource = null;
          button.textContent = "Start Live Stream";
          button.className =
            "px-3 py-2 bg-green-600 text-white rounded hover:bg-green-700";
        } else {
          // Start streaming
          const level = document.getElementById("log-level-filter").value;
          const entityType = document.getElementById("log-entity-filter").value;

          const params = new URLSearchParams();
          if (level) params.append("level", level);
          if (entityType) params.append("entity_type", entityType);

          // EventSource doesn't support custom headers, so we need to pass auth in query params
          // or rely on cookie-based auth
          const url = `${window.ROOT_PATH || ""}/admin/logs/stream?${params}`;
          logStreamSource = new EventSource(url, { withCredentials: true });

          logStreamSource.onmessage = (event) => {
            const data = JSON.parse(event.data);
            if (data.type === "log_entry") {
              prependLog(data.data);
            }
          };

          logStreamSource.onerror = (error) => {
            console.error("Stream error:", error);
            toggleLogStream(); // Stop on error
          };

          button.textContent = "Stop Live Stream";
          button.className =
            "px-3 py-2 bg-red-600 text-white rounded hover:bg-red-700";
        }
      }

      function prependLog(log) {
        const tbody = document.getElementById("logs-tbody");
        const row = document.createElement("tr");
        row.className = "hover:bg-gray-50 dark:hover:bg-gray-700 animate-pulse";

        const timestamp = new Date(log.timestamp).toLocaleString();
        const levelClass = getLevelClass(log.level);
        const entity = log.entity_name || log.entity_id || "-";

        row.innerHTML = `
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
            ${timestamp}
          </td>
          <td class="px-6 py-4 whitespace-nowrap">
            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${levelClass}">
              ${log.level}
            </span>
          </td>
          <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
            ${log.entity_type ? `${log.entity_type}: ${entity}` : entity}
          </td>
          <td class="px-6 py-4 text-sm text-gray-900 dark:text-gray-100">
            ${escapeHtml(log.message)}
          </td>
        `;

        tbody.insertBefore(row, tbody.firstChild);

        // Remove animation after a moment
        setTimeout(() => row.classList.remove("animate-pulse"), 1000);

        // Limit displayed rows
        while (tbody.children.length > logsPerPage) {
          tbody.removeChild(tbody.lastChild);
        }
      }

      async function exportLogs(format) {
        const level = document.getElementById("log-level-filter").value;
        const entityType = document.getElementById("log-entity-filter").value;
        const search = document.getElementById("log-search").value;

        const params = new URLSearchParams({ format });
        if (level) params.append("level", level);
        if (entityType) params.append("entity_type", entityType);
        if (search) params.append("search", search);

        try {
          // Use the same auth approach as other admin endpoints
          const headers = {};
          const token = localStorage.getItem("token");
          if (token) {
            headers["Authorization"] = `Bearer ${token}`;
          }

          const response = await fetch(
            `${window.ROOT_PATH || ""}/admin/logs/export?${params}`,
            {
              headers: headers,
              credentials: "same-origin",
            },
          );

          if (!response.ok) throw new Error(`HTTP ${response.status}`);

          const blob = await response.blob();
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.href = url;
          a.download = `logs_export.${format}`;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          window.URL.revokeObjectURL(url);
        } catch (error) {
          console.error("Error exporting logs:", error);
          showErrorMessage("Failed to export logs");
        }
      }

      function showErrorMessage(message) {
        const toast = document.createElement("div");
        toast.className =
          "fixed top-4 right-4 bg-red-600 text-white px-6 py-3 rounded-lg shadow-lg z-50 animate-pulse";
        toast.textContent = message;
        document.body.appendChild(toast);
        setTimeout(() => toast.remove(), 5000);
      }

      function showSuccessMessage(message) {
        const toast = document.createElement("div");
        toast.className =
          "fixed top-4 right-4 bg-green-600 text-white px-6 py-3 rounded-lg shadow-lg z-50";
        toast.textContent = message;
        document.body.appendChild(toast);
        setTimeout(() => toast.remove(), 3000);
      }

      async function showLogFiles() {
        try {
          const headers = {};
          const token = localStorage.getItem("token");
          if (token) {
            headers["Authorization"] = `Bearer ${token}`;
          }

          const response = await fetch(
            `${window.ROOT_PATH || ""}/admin/logs/file`,
            {
              headers: headers,
              credentials: "same-origin",
            },
          );

          if (!response.ok) {
            const errorData = await response.json().catch(() => ({}));
            throw new Error(errorData.detail || `HTTP ${response.status}`);
          }

          const data = await response.json();

          if (data.files && data.files.length > 0) {
            // Create a modal to show available files
            const modal = document.createElement("div");
            modal.className =
              "fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50";
            modal.innerHTML = `
              <div class="bg-white rounded-lg p-6 max-w-md w-full max-h-96 overflow-y-auto">
                <h3 class="text-lg font-bold mb-4">Available Log Files</h3>
                <p class="text-sm text-gray-600 mb-4">Directory: ${data.log_directory}</p>
                <ul class="space-y-2">
                  ${data.files
                    .map(
                      (file) => `
                    <li class="flex justify-between items-center p-2 hover:bg-gray-100 rounded">
                      <div>
                        <div class="font-medium">${file.name}</div>
                        <div class="text-xs text-gray-500">
                          ${(file.size / 1024).toFixed(1)} KB - ${new Date(file.modified).toLocaleString()}
                        </div>
                      </div>
                      <button onclick="downloadLogFile('${file.name}')"
                              class="px-3 py-1 bg-blue-600 text-white text-sm rounded hover:bg-blue-700">
                        Download
                      </button>
                    </li>
                  `,
                    )
                    .join("")}
                </ul>
                <button onclick="this.closest('.fixed').remove()"
                        class="mt-4 px-4 py-2 bg-gray-600 text-white rounded hover:bg-gray-700 w-full">
                  Close
                </button>
              </div>
            `;
            document.body.appendChild(modal);
          } else {
            showErrorMessage("No log files available");
          }
        } catch (error) {
          console.error("Error fetching log files:", error);
          showErrorMessage(error.message || "Failed to fetch log files");
        }
      }

      async function downloadLogFile(filename) {
        try {
          const headers = {};
          const token = localStorage.getItem("token");
          if (token) {
            headers["Authorization"] = `Bearer ${token}`;
          }

          const response = await fetch(
            `${window.ROOT_PATH || ""}/admin/logs/file?filename=${encodeURIComponent(filename)}`,
            {
              headers: headers,
              credentials: "same-origin",
            },
          );

          if (!response.ok) {
            const errorData = await response.json().catch(() => ({}));
            throw new Error(errorData.detail || `HTTP ${response.status}`);
          }

          const blob = await response.blob();
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.href = url;
          a.download = filename;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          window.URL.revokeObjectURL(url);

          // Close the modal if it exists
          const modal = document.querySelector(".fixed.inset-0");
          if (modal) modal.remove();

          showSuccessMessage(`Downloaded: ${filename}`);
        } catch (error) {
          console.error("Error downloading log file:", error);
          showErrorMessage(error.message || "Failed to download log file");
        }
      }

      function previousLogPage() {
        if (currentLogPage > 0) {
          currentLogPage--;
          refreshLogs();
        }
      }

      function nextLogPage() {
        currentLogPage++;
        refreshLogs();
      }

      function escapeHtml(text) {
        const div = document.createElement("div");
        div.textContent = text;
        return div.innerHTML;
      }

      // Add event listeners for log filters
      document.addEventListener("DOMContentLoaded", () => {
        const logFilters = [
          "log-level-filter",
          "log-entity-filter",
          "log-search",
        ];
        logFilters.forEach((id) => {
          const element = document.getElementById(id);
          if (element) {
            element.addEventListener("change", () => {
              currentLogPage = 0;
              refreshLogs();
            });

            // For search input, debounce
            if (id === "log-search") {
              let timeout;
              element.addEventListener("input", () => {
                clearTimeout(timeout);
                timeout = setTimeout(() => {
                  currentLogPage = 0;
                  refreshLogs();
                }, 500);
              });
            }
          }
        });

        // Load logs when logs tab is clicked
        const logsTab = document.getElementById("tab-logs");
        if (logsTab) {
          logsTab.addEventListener("click", () => {
            setTimeout(refreshLogs, 100);
          });
        }

        // ================================
        // BULK IMPORT FUNCTIONALITY
        // ================================

        let bulkImportData = null;

        // Open bulk import modal - make it globally available
        window.openBulkImportModal = function () {
          console.log("openBulkImportModal called");
          const modal = document.getElementById("bulk-import-modal");
          console.log("Modal element:", modal);
          if (modal) {
            modal.classList.remove("hidden");
            resetBulkImportModal();
          } else {
            console.error("Modal element not found!");
          }
        };

        // Close bulk import modal
        window.closeBulkImportModal = function () {
          document.getElementById("bulk-import-modal").classList.add("hidden");
          resetBulkImportModal();
        };

        // Reset modal to initial state
        function resetBulkImportModal() {
          // Reset radio buttons
          document.querySelector(
            'input[name="import-method"][value="file"]',
          ).checked = true;
          toggleImportMethod("file");

          // Clear file input
          document.getElementById("bulk-import-file").value = "";
          document.getElementById("file-info").classList.add("hidden");

          // Clear JSON textarea
          document.getElementById("bulk-import-json").value = "";

          // Hide sections
          document.getElementById("import-preview").classList.add("hidden");
          document.getElementById("import-status").classList.add("hidden");
          document.getElementById("import-loading").classList.add("hidden");

          // Reset validation status
          document.getElementById("json-validation-status").textContent = "";
          document.getElementById("json-validation-status").className =
            "text-sm";

          // Disable submit button
          document.getElementById("import-submit-btn").disabled = true;

          // Reset global data
          bulkImportData = null;
        }

        // Toggle between file upload and JSON paste
        window.toggleImportMethod = function (method) {
          const fileSection = document.getElementById("file-upload-section");
          const pasteSection = document.getElementById("json-paste-section");

          if (method === "file") {
            fileSection.classList.remove("hidden");
            pasteSection.classList.add("hidden");
          } else {
            fileSection.classList.add("hidden");
            pasteSection.classList.remove("hidden");
          }

          // Clear preview when switching methods
          document.getElementById("import-preview").classList.add("hidden");
          document.getElementById("import-submit-btn").disabled = true;
          bulkImportData = null;
        };

        // Handle file selection
        window.handleFileSelect = function (input) {
          const file = input.files[0];
          if (!file) {
            document.getElementById("file-info").classList.add("hidden");
            return;
          }

          // Validate file type
          if (!file.name.toLowerCase().endsWith(".json")) {
            showImportError("Please select a JSON file.");
            input.value = "";
            return;
          }

          // Show file info
          document.getElementById("file-name").textContent = file.name;
          document.getElementById("file-size").textContent =
            `(${formatFileSize(file.size)})`;
          document.getElementById("file-info").classList.remove("hidden");

          // Read file content
          const reader = new FileReader();
          reader.onload = function (e) {
            try {
              const jsonData = JSON.parse(e.target.result);
              processImportData(jsonData);
            } catch (error) {
              showImportError(`Invalid JSON file: ${error.message}`);
              input.value = "";
              document.getElementById("file-info").classList.add("hidden");
            }
          };
          reader.onerror = function () {
            showImportError("Error reading file.");
            input.value = "";
            document.getElementById("file-info").classList.add("hidden");
          };
          reader.readAsText(file);
        };

        // Validate JSON input from textarea
        window.validateJsonInput = function () {
          const jsonText = document
            .getElementById("bulk-import-json")
            .value.trim();
          const statusElement = document.getElementById(
            "json-validation-status",
          );

          if (!jsonText) {
            statusElement.textContent = "Please enter JSON data";
            statusElement.className =
              "text-sm text-yellow-600 dark:text-yellow-400";
            return;
          }

          try {
            const jsonData = JSON.parse(jsonText);

            // Validate structure with helpful messages
            if (!Array.isArray(jsonData)) {
              statusElement.textContent =
                "✗ JSON must be an array of tool objects [{}], not a single object {}";
              statusElement.className =
                "text-sm text-red-600 dark:text-red-400";
              document.getElementById("import-preview").classList.add("hidden");
              document.getElementById("import-submit-btn").disabled = true;
              bulkImportData = null;
              return;
            }

            if (jsonData.length === 0) {
              statusElement.textContent =
                "✗ Array cannot be empty - add at least one tool";
              statusElement.className =
                "text-sm text-red-600 dark:text-red-400";
              document.getElementById("import-preview").classList.add("hidden");
              document.getElementById("import-submit-btn").disabled = true;
              bulkImportData = null;
              return;
            }

            // Success with helpful info
            const toolCount = jsonData.length;
            const toolsWithNames = jsonData.filter((tool) => tool && tool.name);

            if (toolsWithNames.length === toolCount) {
              statusElement.textContent = `✓ Valid JSON array with ${toolCount} tool(s) - names will be auto-fixed for compatibility`;
              statusElement.className =
                "text-sm text-green-600 dark:text-green-400";
            } else {
              statusElement.textContent = `⚠ Valid JSON but ${toolCount - toolsWithNames.length} tool(s) missing required name field`;
              statusElement.className =
                "text-sm text-yellow-600 dark:text-yellow-400";
            }

            processImportData(jsonData);
          } catch (error) {
            let helpText = "";
            if (error.message.includes("Unexpected")) {
              helpText = " (Check for missing commas, quotes, or brackets)";
            }
            statusElement.textContent = `✗ Invalid JSON: ${error.message}${helpText}`;
            statusElement.className = "text-sm text-red-600 dark:text-red-400";
            document.getElementById("import-preview").classList.add("hidden");
            document.getElementById("import-submit-btn").disabled = true;
            bulkImportData = null;
          }
        };

        // Process and validate import data
        function processImportData(data) {
          try {
            // Validate data structure
            if (!Array.isArray(data)) {
              throw new Error("Data must be an array of tool definitions");
            }

            if (data.length === 0) {
              throw new Error("Array cannot be empty");
            }

            if (data.length > 200) {
              throw new Error(
                `Too many tools (${data.length}). Maximum 200 allowed.`,
              );
            }

            // Auto-fix and validate each tool
            const errors = [];
            const fixedData = data.map((tool, index) => {
              if (!tool || typeof tool !== "object") {
                errors.push(`Item ${index + 1}: Must be an object`);
                return tool;
              }

              // Create a copy to avoid modifying original
              const fixedTool = { ...tool };

              // Fix tool name to meet validation requirements
              if (fixedTool.name) {
                const originalName = fixedTool.name;
                // Convert to valid format: start with letter, only letters/numbers/dots/underscores/hyphens
                fixedTool.name = String(originalName)
                  .trim()
                  .replace(/\s+/g, "_") // Replace spaces with underscores
                  .replace(/[^a-zA-Z0-9._-]/g, "") // Remove invalid characters
                  .replace(/^[^a-zA-Z]/, "tool_") // Ensure starts with letter
                  .toLowerCase();

                if (fixedTool.name !== originalName) {
                  console.log(
                    `Auto-fixed tool name: "${originalName}" -> "${fixedTool.name}"`,
                  );
                }
              }

              // Fix tags if present (tags must be an array, not a string)
              if (fixedTool.tags) {
                const originalTags = fixedTool.tags;
                if (typeof fixedTool.tags === "string") {
                  // Convert comma-separated string to array of strings
                  fixedTool.tags = fixedTool.tags
                    .split(",") // Split by comma
                    .map((tag) => tag.trim()) // Trim whitespace
                    .filter((tag) => tag.length >= 2) // Remove empty/too short tags
                    .map((tag) => tag.toLowerCase()) // Convert to lowercase
                    .map((tag) => tag.replace(/[^a-z0-9\-\:\.]/g, "")) // Remove invalid characters
                    .filter((tag) => tag.length >= 2); // Filter again after cleaning

                  if (
                    JSON.stringify(fixedTool.tags) !==
                    JSON.stringify(originalTags)
                  ) {
                    console.log(
                      `Auto-fixed tags: "${originalTags}" -> ${JSON.stringify(fixedTool.tags)}`,
                    );
                  }
                } else if (Array.isArray(fixedTool.tags)) {
                  // Clean up array of tags
                  fixedTool.tags = fixedTool.tags
                    .map((tag) => String(tag).trim().toLowerCase())
                    .map((tag) => tag.replace(/[^a-z0-9\-\:\.]/g, ""))
                    .filter((tag) => tag.length >= 2);

                  if (
                    JSON.stringify(fixedTool.tags) !==
                    JSON.stringify(originalTags)
                  ) {
                    console.log(
                      `Auto-fixed tags array: ${JSON.stringify(originalTags)} -> ${JSON.stringify(fixedTool.tags)}`,
                    );
                  }
                }
              }

              // Only name is strictly required
              const required = ["name"];
              const missing = required.filter(
                (field) =>
                  !fixedTool[field] ||
                  (typeof fixedTool[field] === "string" &&
                    fixedTool[field].trim() === ""),
              );
              if (missing.length > 0) {
                errors.push(
                  `Item ${index + 1}: Missing required fields: ${missing.join(", ")}`,
                );
              }

              // Warn about missing recommended fields but don't block import
              const recommended = ["url"];
              const missingRecommended = recommended.filter(
                (field) =>
                  !fixedTool[field] ||
                  (typeof fixedTool[field] === "string" &&
                    fixedTool[field].trim() === ""),
              );
              if (missingRecommended.length > 0) {
                console.warn(
                  `Item ${index + 1} (${fixedTool.name || "unnamed"}): Missing recommended fields: ${missingRecommended.join(", ")}`,
                );
              }

              return fixedTool;
            });

            if (errors.length > 0) {
              throw new Error(
                `Validation errors:\\n${errors.slice(0, 5).join("\\n")}${errors.length > 5 ? `\\n... and ${errors.length - 5} more errors` : ""}`,
              );
            }

            // Store the fixed data instead of original
            bulkImportData = fixedData;

            // Show preview
            showImportPreview(fixedData);

            // Enable submit button
            document.getElementById("import-submit-btn").disabled = false;

            // Clear any previous error messages
            document.getElementById("import-status").classList.add("hidden");
          } catch (error) {
            showImportError(error.message);
            bulkImportData = null;
            document.getElementById("import-submit-btn").disabled = true;
          }
        } // Show import preview
        function showImportPreview(data) {
          document.getElementById("preview-count").textContent = data.length;

          // Populate preview list
          const previewList = document.getElementById("preview-list");
          previewList.innerHTML = "";

          data.slice(0, 10).forEach((tool, index) => {
            const li = document.createElement("li");
            li.className = "flex justify-between";
            li.innerHTML = `
              <span class="truncate">${escapeHtml(tool.name || "Unnamed")}</span>
              <span class="ml-2 text-gray-500">${escapeHtml(tool.integrationType || "REST")}</span>
            `;
            previewList.appendChild(li);
          });

          if (data.length > 10) {
            const li = document.createElement("li");
            li.className = "text-gray-500 italic";
            li.textContent = `... and ${data.length - 10} more tools`;
            previewList.appendChild(li);
          }

          document.getElementById("import-preview").classList.remove("hidden");
        }

        // Toggle validation guide visibility
        window.toggleValidationGuide = function () {
          const guide = document.getElementById("validation-guide");
          const toggle = document.getElementById("validation-guide-toggle");

          if (guide.classList.contains("hidden")) {
            guide.classList.remove("hidden");
            toggle.textContent = "Hide Validation Rules";
          } else {
            guide.classList.add("hidden");
            toggle.textContent = "Show Validation Rules";
          }
        };

        // Toggle preview details
        window.togglePreviewDetails = function () {
          const details = document.getElementById("preview-details");
          const toggleText = document.getElementById("preview-toggle-text");

          if (details.classList.contains("hidden")) {
            details.classList.remove("hidden");
            toggleText.textContent = "Hide Details";
          } else {
            details.classList.add("hidden");
            toggleText.textContent = "Show Details";
          }
        };

        // Submit bulk import
        window.submitBulkImport = async function () {
          if (!bulkImportData) {
            showImportError("No valid data to import");
            return;
          }

          // Show loading
          document.getElementById("import-loading").classList.remove("hidden");
          document.getElementById("import-submit-btn").disabled = true;

          try {
            const response = await fetch(
              `${window.location.origin}/admin/tools/import`,
              {
                method: "POST",
                headers: {
                  "Content-Type": "application/json",
                },
                body: JSON.stringify(bulkImportData),
              },
            );

            const result = await response.json();

            // Debug logging
            console.log("Response status:", response.status);
            console.log("Response ok:", response.ok);
            console.log("Result:", result);
            console.log("Result.success:", result.success);
            console.log("Result.created_count:", result.created_count);
            console.log("Result.failed_count:", result.failed_count);
            console.log("Result.errors:", result.errors);

            // Log individual errors for debugging
            if (result.errors && result.errors.length > 0) {
              console.log("Detailed errors:");
              result.errors.forEach((error, index) => {
                console.log(`Error ${index + 1}:`, error);
                if (error.error) {
                  console.log(`  Error message:`, error.error.message);
                  console.log(
                    `  Full error object:`,
                    JSON.stringify(error.error, null, 2),
                  );
                }
              });
            }

            // Hide loading
            document.getElementById("import-loading").classList.add("hidden");

            if (response.ok) {
              if (result.success) {
                // Complete success
                showImportSuccess(result);

                // Auto-close modal after success and refresh page
                setTimeout(() => {
                  closeBulkImportModal();
                  location.reload(); // Refresh to show new tools
                }, 3000);
              } else if (result.created_count > 0) {
                // Partial success - some tools imported successfully
                showImportSuccess(result);

                // Auto-close modal after partial success and refresh page
                setTimeout(() => {
                  closeBulkImportModal();
                  location.reload(); // Refresh to show new tools
                }, 5000); // Longer delay to see the message
              } else {
                // Complete failure
                showImportError(result.message || "All tools failed to import");
                document.getElementById("import-submit-btn").disabled = false;
              }
            } else {
              showImportError(result.message || "Import failed");
              document.getElementById("import-submit-btn").disabled = false;
            }
          } catch (error) {
            document.getElementById("import-loading").classList.add("hidden");
            showImportError(`Network error: ${error.message}`);
            document.getElementById("import-submit-btn").disabled = false;
          }
        };

        // Show import success message
        function showImportSuccess(result) {
          const statusDiv = document.getElementById("import-status");
          const isPartialSuccess = result.failed_count > 0;
          const bgColor = isPartialSuccess ? "yellow" : "green";
          const textColor = isPartialSuccess ? "yellow" : "green";

          statusDiv.innerHTML = `
            <div class="bg-${bgColor}-50 dark:bg-${bgColor}-900 border border-${bgColor}-200 dark:border-${bgColor}-800 rounded-md p-4">
              <div class="flex">
                <div class="flex-shrink-0">
                  <svg class="h-5 w-5 text-${textColor}-400" fill="currentColor" viewBox="0 0 20 20">
                    <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path>
                  </svg>
                </div>
                <div class="ml-3">
                  <h3 class="text-sm font-medium text-${textColor}-800 dark:text-${textColor}-200">
                    ${isPartialSuccess ? "Import Partially Completed" : "Import Completed Successfully"}
                  </h3>
                  <div class="mt-2 text-sm text-${textColor}-700 dark:text-${textColor}-300">
                    <p><strong>${result.created_count}</strong> tools imported successfully</p>
                    ${result.failed_count > 0 ? `<p><strong>${result.failed_count}</strong> tools failed to import</p>` : ""}
                    ${
                      result.errors && result.errors.length > 0
                        ? `
                      <details class="mt-2">
                        <summary class="cursor-pointer">View errors</summary>
                        <ul class="mt-1 list-disc list-inside text-xs">
                          ${result.errors
                            .slice(0, 5)
                            .map(
                              (error) =>
                                `<li>${error.name || "Tool"}: ${error.error?.message || "Unknown error"}</li>`,
                            )
                            .join("")}
                          ${result.errors.length > 5 ? `<li>... and ${result.errors.length - 5} more errors</li>` : ""}
                        </ul>
                      </details>
                    `
                        : ""
                    }
                    <p class="mt-2 text-xs">Page will refresh automatically...</p>
                  </div>
                </div>
              </div>
            </div>
          `;
          statusDiv.classList.remove("hidden");
        }

        // Show import error message
        function showImportError(message) {
          const statusDiv = document.getElementById("import-status");
          statusDiv.innerHTML = `
            <div class="bg-red-50 dark:bg-red-900 border border-red-200 dark:border-red-800 rounded-md p-4">
              <div class="flex">
                <div class="flex-shrink-0">
                  <svg class="h-5 w-5 text-red-400" fill="currentColor" viewBox="0 0 20 20">
                    <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"></path>
                  </svg>
                </div>
                <div class="ml-3">
                  <h3 class="text-sm font-medium text-red-800 dark:text-red-200">
                    Import Error
                  </h3>
                  <div class="mt-2 text-sm text-red-700 dark:text-red-300">
                    <p>${escapeHtml(message)}</p>
                  </div>
                </div>
              </div>
            </div>
          `;
          statusDiv.classList.remove("hidden");
        }

        // Format file size
        function formatFileSize(bytes) {
          if (bytes === 0) return "0 Bytes";
          const k = 1024;
          const sizes = ["Bytes", "KB", "MB", "GB"];
          const i = Math.floor(Math.log(bytes) / Math.log(k));
          return (
            parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i]
          );
        }

        // Auto-trigger JSON validation when typing in textarea
        document.addEventListener("DOMContentLoaded", function () {
          const jsonTextarea = document.getElementById("bulk-import-json");
          if (jsonTextarea) {
            let validationTimeout;
            jsonTextarea.addEventListener("input", function () {
              clearTimeout(validationTimeout);
              validationTimeout = setTimeout(function () {
                if (jsonTextarea.value.trim()) {
                  validateJsonInput();
                }
              }, 1000); // Validate 1 second after user stops typing
            });
          }
        });

        // Dropdown Functions
        window.toggleBulkImportDropdown = function () {
          const dropdown = document.getElementById("bulk-import-dropdown");
          dropdown.classList.toggle("hidden");
        };

        window.toggleDropdownImportMethod = function (method) {
          const fileSection = document.getElementById("dropdown-file-section");
          const pasteSection = document.getElementById(
            "dropdown-paste-section",
          );

          if (method === "file") {
            fileSection.classList.remove("hidden");
            pasteSection.classList.add("hidden");
          } else {
            fileSection.classList.add("hidden");
            pasteSection.classList.remove("hidden");
          }
          resetDropdownImport();
        };

        window.handleDropdownFileSelect = function (input) {
          const fileInfo = document.getElementById("dropdown-file-info");
          const preview = document.getElementById("dropdown-preview");
          const status = document.getElementById("dropdown-status");

          if (!input.files[0]) {
            resetDropdownImport();
            return;
          }

          const file = input.files[0];
          fileInfo.textContent = `Selected: ${file.name} (${(file.size / 1024).toFixed(1)} KB)`;
          fileInfo.classList.remove("hidden");

          const reader = new FileReader();
          reader.onload = function (e) {
            try {
              const data = JSON.parse(e.target.result);
              validateDropdownData(data);
            } catch (error) {
              showDropdownStatus("error", `Invalid JSON: ${error.message}`);
            }
          };
          reader.readAsText(file);
        };

        window.validateDropdownJson = function () {
          const textarea = document.getElementById("dropdown-json-textarea");
          const status = document.getElementById("dropdown-json-status");

          if (!textarea.value.trim()) {
            status.textContent = "";
            document.getElementById("dropdown-import-btn").disabled = true;
            document.getElementById("dropdown-preview").classList.add("hidden");
            return;
          }

          try {
            const data = JSON.parse(textarea.value);
            status.innerHTML =
              '<span class="text-green-600">✓ Valid JSON</span>';
            validateDropdownData(data);
          } catch (error) {
            status.innerHTML = `<span class="text-red-600">✗ Invalid JSON: ${error.message}</span>`;
            document.getElementById("dropdown-import-btn").disabled = true;
            document.getElementById("dropdown-preview").classList.add("hidden");
          }
        };

        window.validateDropdownData = function (data) {
          const preview = document.getElementById("dropdown-preview");
          const count = document.getElementById("dropdown-preview-count");
          const importBtn = document.getElementById("dropdown-import-btn");

          if (!Array.isArray(data)) {
            showDropdownStatus("error", "Data must be an array of tools");
            return;
          }

          if (data.length === 0) {
            showDropdownStatus("error", "Array cannot be empty");
            return;
          }

          if (data.length > 200) {
            showDropdownStatus(
              "error",
              "Cannot import more than 200 tools at once",
            );
            return;
          }

          count.textContent = data.length;
          preview.classList.remove("hidden");
          importBtn.disabled = false;
          showDropdownStatus(
            "success",
            `${data.length} tools ready for import`,
          );
        };

        window.showDropdownStatus = function (type, message) {
          const status = document.getElementById("dropdown-status");
          status.innerHTML = `<div class="text-${type === "error" ? "red" : "green"}-600">${message}</div>`;
          status.classList.remove("hidden");
        };

        window.resetDropdownImport = function () {
          document.getElementById("dropdown-file-input").value = "";
          document.getElementById("dropdown-json-textarea").value = "";
          document.getElementById("dropdown-file-info").classList.add("hidden");
          document.getElementById("dropdown-json-status").textContent = "";
          document.getElementById("dropdown-preview").classList.add("hidden");
          document.getElementById("dropdown-status").classList.add("hidden");
          document.getElementById("dropdown-import-btn").disabled = true;
        };

        window.submitDropdownImport = async function () {
          const importBtn = document.getElementById("dropdown-import-btn");
          const status = document.getElementById("dropdown-status");

          let data;
          const fileInput = document.getElementById("dropdown-file-input");
          const textarea = document.getElementById("dropdown-json-textarea");

          if (fileInput.files[0]) {
            const reader = new FileReader();
            reader.onload = async function (e) {
              try {
                data = JSON.parse(e.target.result);
                await performDropdownImport(data);
              } catch (error) {
                showDropdownStatus(
                  "error",
                  `Failed to parse file: ${error.message}`,
                );
              }
            };
            reader.readAsText(fileInput.files[0]);
          } else if (textarea.value.trim()) {
            try {
              data = JSON.parse(textarea.value);
              await performDropdownImport(data);
            } catch (error) {
              showDropdownStatus("error", `Invalid JSON: ${error.message}`);
            }
          }
        };

        window.performDropdownImport = async function (data) {
          const importBtn = document.getElementById("dropdown-import-btn");
          const status = document.getElementById("dropdown-status");

          importBtn.disabled = true;
          importBtn.textContent = "Importing...";

          try {
            const response = await fetch("/admin/tools/import", {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
              },
              body: JSON.stringify(data),
            });

            const result = await response.json();

            if (response.ok) {
              showDropdownStatus(
                "success",
                `✅ Successfully imported ${result.imported} tools`,
              );
              resetDropdownImport();
              setTimeout(() => {
                window.location.reload();
              }, 2000);
            } else {
              showDropdownStatus(
                "error",
                `❌ Import failed: ${result.detail || "Unknown error"}`,
              );
            }
          } catch (error) {
            showDropdownStatus("error", `❌ Network error: ${error.message}`);
          } finally {
            importBtn.disabled = false;
            importBtn.textContent = "Import Tools";
          }
        };

        // Close dropdown when clicking outside
        document.addEventListener("click", function (event) {
          const dropdown = document.getElementById("bulk-import-dropdown");
          const button = document.getElementById("bulk-import-dropdown-btn");

          if (
            dropdown &&
            !dropdown.contains(event.target) &&
            !button.contains(event.target)
          ) {
            dropdown.classList.add("hidden");
          }
        });
      });
    </script>

    <!-- Bulk Import Modal -->
    <div
      id="bulk-import-modal-2"
      class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50"
    >
      <div
        class="relative top-20 mx-auto p-5 border w-11/12 md:w-3/4 lg:w-1/2 shadow-lg rounded-md bg-white dark:bg-gray-800"
      >
        <div class="mt-3">
          <!-- Modal Header -->
          <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">
              Bulk Import Tools
            </h3>
            <button
              onclick="closeBulkImportModal()"
              class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
            >
              <svg
                class="w-6 h-6"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M6 18L18 6M6 6l12 12"
                ></path>
              </svg>
            </button>
          </div>

          <!-- Modal Content -->
          <div class="space-y-4">
            <!-- Instructions -->
            <div
              class="bg-blue-50 dark:bg-blue-900 border border-blue-200 dark:border-blue-800 rounded-md p-3"
            >
              <div class="flex">
                <div class="flex-shrink-0">
                  <svg
                    class="h-5 w-5 text-blue-400"
                    fill="currentColor"
                    viewBox="0 0 20 20"
                  >
                    <path
                      fill-rule="evenodd"
                      d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z"
                      clip-rule="evenodd"
                    ></path>
                  </svg>
                </div>
                <div class="ml-3">
                  <h3
                    class="text-sm font-medium text-blue-800 dark:text-blue-200"
                  >
                    Import Instructions
                  </h3>
                  <div class="mt-2 text-sm text-blue-700 dark:text-blue-300">
                    <div class="mb-3">
                      <button
                        onclick="toggleValidationGuide()"
                        class="inline-flex items-center text-xs text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-200"
                      >
                        <svg
                          class="w-3 h-3 mr-1"
                          fill="none"
                          stroke="currentColor"
                          viewBox="0 0 24 24"
                        >
                          <path
                            stroke-linecap="round"
                            stroke-linejoin="round"
                            stroke-width="2"
                            d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                          ></path>
                        </svg>
                        <span id="validation-guide-toggle"
                          >Show Validation Rules</span
                        >
                      </button>
                    </div>

                    <div
                      id="validation-guide"
                      class="hidden bg-blue-50 dark:bg-blue-900 border border-blue-200 dark:border-blue-700 rounded-md p-3 mb-3 text-xs"
                    >
                      <h5
                        class="font-semibold mb-2 text-blue-800 dark:text-blue-200"
                      >
                        📋 JSON Validation Rules
                      </h5>
                      <div class="space-y-2">
                        <div>
                          <strong class="text-green-700 dark:text-green-300"
                            >✅ Required:</strong
                          >
                          <code
                            class="bg-blue-100 dark:bg-blue-800 px-1 rounded"
                            >name</code
                          >
                          - must start with letter, only
                          letters/numbers/dots/underscores/hyphens
                        </div>
                        <div>
                          <strong class="text-blue-700 dark:text-blue-300"
                            >🔹 Optional:</strong
                          >
                          <code
                            class="bg-blue-100 dark:bg-blue-800 px-1 rounded"
                            >url</code
                          >
                          (http/https/ws/wss only),
                          <code
                            class="bg-blue-100 dark:bg-blue-800 px-1 rounded"
                            >description</code
                          >,
                          <code
                            class="bg-blue-100 dark:bg-blue-800 px-1 rounded"
                            >tags</code
                          >
                          (array only)
                        </div>
                        <div>
                          <strong class="text-orange-700 dark:text-orange-300"
                            >⚠️ Case Sensitive:</strong
                          >
                          <code
                            class="bg-blue-100 dark:bg-blue-800 px-1 rounded"
                            >requestType</code
                          >
                          ("GET", "POST"),
                          <code
                            class="bg-blue-100 dark:bg-blue-800 px-1 rounded"
                            >integrationType</code
                          >
                          ("REST", "MCP")
                        </div>
                        <div>
                          <strong class="text-red-700 dark:text-red-300"
                            >❌ Not Allowed:</strong
                          >
                          Names starting with numbers, FTP URLs, tag strings
                          "tag1,tag2" (use ["tag1","tag2"])
                        </div>
                        <div
                          class="pt-1 border-t border-blue-200 dark:border-blue-700"
                        >
                          <strong class="text-purple-700 dark:text-purple-300"
                            >🔧 Auto-Fixed:</strong
                          >
                          Spaces in names, tag strings → arrays, case
                          normalization
                        </div>
                      </div>
                    </div>

                    <ul class="list-disc pl-5 space-y-1"></ul>
                  </div>
                </div>
              </div>
            </div>

            <!-- Input Method Selection -->
            <div class="space-y-3">
              <h4 class="text-sm font-medium text-gray-900 dark:text-gray-100">
                Choose Import Method:
              </h4>

              <!-- Radio buttons for input method -->
              <div class="flex space-x-6">
                <label class="flex items-center">
                  <input
                    type="radio"
                    name="import-method"
                    value="file"
                    checked
                    onchange="toggleImportMethod(this.value)"
                    class="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300"
                  />
                  <span class="ml-2 text-sm text-gray-700 dark:text-gray-300"
                    >Upload JSON File</span
                  >
                </label>
                <label class="flex items-center">
                  <input
                    type="radio"
                    name="import-method"
                    value="paste"
                    onchange="toggleImportMethod(this.value)"
                    class="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300"
                  />
                  <span class="ml-2 text-sm text-gray-700 dark:text-gray-300"
                    >Paste JSON Data</span
                  >
                </label>
              </div>
            </div>

            <!-- File Upload Section -->
            <div id="file-upload-section" class="space-y-3">
              <label
                class="block text-sm font-medium text-gray-700 dark:text-gray-300"
              >
                Select JSON File
              </label>
              <div
                class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-md dark:border-gray-600"
              >
                <div class="space-y-1 text-center">
                  <svg
                    class="mx-auto h-12 w-12 text-gray-400"
                    stroke="currentColor"
                    fill="none"
                    viewBox="0 0 48 48"
                  >
                    <path
                      d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02"
                      stroke-width="2"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                    />
                  </svg>
                  <div class="flex text-sm text-gray-600 dark:text-gray-400">
                    <label
                      for="bulk-import-file"
                      class="relative cursor-pointer bg-white dark:bg-gray-800 rounded-md font-medium text-indigo-600 hover:text-indigo-500 focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-indigo-500"
                    >
                      <span>Upload a file</span>
                      <input
                        id="bulk-import-file"
                        name="bulk-import-file"
                        type="file"
                        accept=".json"
                        onchange="handleFileSelect(this)"
                        class="sr-only"
                      />
                    </label>
                    <p class="pl-1">or drag and drop</p>
                  </div>
                  <p class="text-xs text-gray-500 dark:text-gray-400">
                    JSON files only
                  </p>
                </div>
              </div>
              <!-- File info display -->
              <div id="file-info" class="hidden mt-2">
                <div
                  class="flex items-center space-x-2 text-sm text-gray-600 dark:text-gray-400"
                >
                  <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                    <path
                      fill-rule="evenodd"
                      d="M3 17a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm3.293-7.707a1 1 0 011.414 0L9 10.586V3a1 1 0 112 0v7.586l1.293-1.293a1 1 0 111.414 1.414l-3 3a1 1 0 01-1.414 0l-3-3a1 1 0 010-1.414z"
                      clip-rule="evenodd"
                    ></path>
                  </svg>
                  <span id="file-name"></span>
                  <span id="file-size" class="text-xs text-gray-500"></span>
                </div>
              </div>
            </div>

            <!-- JSON Paste Section -->
            <div id="json-paste-section" class="space-y-3 hidden">
              <label
                for="bulk-import-json"
                class="block text-sm font-medium text-gray-700 dark:text-gray-300"
              >
                Paste JSON Data
              </label>
              <textarea
                id="bulk-import-json"
                name="bulk-import-json"
                rows="12"
                placeholder="[&#10;  {&#10;    &quot;name&quot;: &quot;Books Search&quot;,&#10;    &quot;url&quot;: &quot;https://www.googleapis.com/books/v1/volumes&quot;,&#10;    &quot;description&quot;: &quot;Search Google Books&quot;,&#10;    &quot;integrationType&quot;: &quot;REST&quot;,&#10;    &quot;requestType&quot;: &quot;GET&quot;,&#10;    &quot;tags&quot;: [&quot;api&quot;, &quot;google&quot;, &quot;books&quot;]&#10;  },&#10;  {&#10;    &quot;name&quot;: &quot;JSON Placeholder Posts&quot;,&#10;    &quot;url&quot;: &quot;https://jsonplaceholder.typicode.com/posts&quot;,&#10;    &quot;integrationType&quot;: &quot;REST&quot;,&#10;    &quot;requestType&quot;: &quot;GET&quot;,&#10;    &quot;headers&quot;: {&quot;Accept&quot;: &quot;application/json&quot;}&#10;  }&#10;]"
                class="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 mt-1 block w-full sm:text-sm border border-gray-300 rounded-md dark:bg-gray-700 dark:border-gray-600 dark:text-gray-300"
              ></textarea>
              <div class="flex justify-between items-center">
                <button
                  type="button"
                  onclick="validateJsonInput()"
                  class="inline-flex items-center px-3 py-1 border border-transparent text-sm leading-4 font-medium rounded-md text-indigo-700 bg-indigo-100 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:bg-indigo-800 dark:text-indigo-200"
                >
                  <svg
                    class="w-4 h-4 mr-1"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="2"
                      d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
                    ></path>
                  </svg>
                  Validate JSON
                </button>
                <span id="json-validation-status" class="text-sm"></span>
              </div>
            </div>

            <!-- Preview Section -->
            <div id="import-preview" class="hidden space-y-3">
              <h4 class="text-sm font-medium text-gray-900 dark:text-gray-100">
                Import Preview
              </h4>
              <div class="bg-gray-50 dark:bg-gray-700 rounded-md p-3">
                <div class="flex items-center justify-between">
                  <span class="text-sm text-gray-700 dark:text-gray-300">
                    <span id="preview-count">0</span> tools ready for import
                  </span>
                  <button
                    type="button"
                    onclick="togglePreviewDetails()"
                    class="text-sm text-indigo-600 hover:text-indigo-500 dark:text-indigo-400"
                  >
                    <span id="preview-toggle-text">Show Details</span>
                  </button>
                </div>
                <div
                  id="preview-details"
                  class="hidden mt-3 max-h-40 overflow-y-auto"
                >
                  <ul
                    id="preview-list"
                    class="text-xs text-gray-600 dark:text-gray-400 space-y-1"
                  >
                    <!-- Preview items will be populated here -->
                  </ul>
                </div>
              </div>
            </div>

            <!-- Status Messages -->
            <div id="import-status" class="hidden">
              <!-- Success/Error messages will be displayed here -->
            </div>

            <!-- Loading Indicator -->
            <div
              id="import-loading"
              class="hidden flex items-center justify-center py-4"
            >
              <div
                class="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600"
              ></div>
              <span class="ml-2 text-sm text-gray-600 dark:text-gray-400"
                >Processing import...</span
              >
            </div>

            <!-- Modal Actions -->
            <div
              class="flex items-center justify-end space-x-3 pt-4 border-t border-gray-200 dark:border-gray-600"
            >
              <button
                type="button"
                onclick="closeBulkImportModal()"
                class="inline-flex items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:bg-gray-700 dark:text-gray-300 dark:border-gray-600 dark:hover:bg-gray-600"
              >
                Cancel
              </button>
              <button
                type="button"
                id="import-submit-btn"
                onclick="submitBulkImport()"
                disabled
                class="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <svg
                  class="w-4 h-4 mr-2"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"
                  ></path>
                </svg>
                Import Tools
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>
